How to cancel an observable sequence

前端 未结 5 831
南笙
南笙 2020-12-17 21:19

I have a very simple IObservable that acts as a pulse generator every 500ms:

var pulses = Observable.GenerateWithTime(0, i => true         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 22:09

    It is an old thread, but just for future reference, here is a simpler way to do it.

    If you have a CancellationToken, you are probably already working with tasks. So, just convert it to a Task and let the framework do the binding:

    using System.Reactive.Threading.Tasks;
    ...
    var task = myObservable.ToTask(cancellationToken);
    

    This will create an internal subscriber that will be disposed when the task is cancelled. This will do the trick in most cases because most observables only produce values if there are subscribers.

    Now, if you have an actual observable that needs to be disposed for some reason (maybe a hot observable that is not important anymore if a parent task is cancelled), this can be achieved with a continuation:

    disposableObservable.ToTask(cancellationToken).ContinueWith(t => {
        if (t.Status == TaskStatus.Canceled)
            disposableObservable.Dispose();
    });
    

提交回复
热议问题