if you have a BlazorServer, then the state of your components-view is stored on the server. You can do so. Register the service as a scoped, this gives the service lifetime equal to your components, if the lifetime is needed more than the register how singleton.
Declare an event in the service, in my case it is RX observable.
Inject the service into the component and subscribe on event.
public partial class YourComponent : IDisposable
{
private IDisposable _disposable = null;
[Inject] public ITimerService TimerService { get; set; }
public string Time { get; set; }
protected override async Task OnInitializedAsync()
{
_disposable = TimerService.Times.Subscribe(OnTimeMessage);
}
private void OnTimeMessage(string time)
{
Time = time;
StateHasChanged();
}
public void Dispose()
{
_disposable?.Dispose();
}
}
public interface ITimeService
{
IObservable<string> Times { get; }
}
public class TimeService : ITimeService
{
private readonly Subject<string> _subject = new();
private Timer _timer;
public TimeService()
{
_timer = new Timer(() =>
{
_subject.OnNext(DateTime.UtcNow.ToString("G"));
}, null, 1000, 1000);
}
public void Dispose()
{
_timer.Dispose();
_subject.Dispose();
}
public void PublishError(string error)
{
_subject.OnNext(error);
}
public IObservable<string> Times()
{
return _subject;
}
}
// In host initialization
//services.AddSingleton<ITimeService, TimeService>();
services.AddScoped<ITimeService, TimeService>();