Код: Выделить всё
using System.Reactive.Linq;
using System.Reactive.Subjects;
// di singleton
public class Observables {
public readonly Subject Subject = new Subject();
public IObservable Observable;
public Observables()
{
Observable = Subject.AsObservable();
}
}
public class ObservableBackgroundServiceManual : BackgroundService {
private readonly ILogger _logger;
private readonly Observables _observables;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0, 1);
public ObservableBackgroundServiceManual(ILogger logger, Observables observables)
{
_logger = logger;
_observables = observables;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_observables.Observable
.Select(value => Observable.FromAsync(async () => await DoBackgroundWork(value)))
.Concat()
.Subscribe(
token: stoppingToken
);
return Task.CompletedTask;
}
private void DoBackgroundWork(int value)
{
// Implement the background work to be done when the observable emits a value
_logger.LogInformation($"Doing background work with value: {value}");
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);
}
}
// Example usage
public class MyObservableService {
private readonly Observables _observables;
public MyObservableService(Observables observables)
{
_observables = observables;
}
public void TriggerChange(int newValue)
{
_observables.Subject.OnNext(newValue);
}
}
Изменить формулировку вопроса, чтобы он был более основан на фактах
Подробнее здесь: https://stackoverflow.com/questions/788 ... n-an-event