How to cancel an observable sequence

前端 未结 5 824
南笙
南笙 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:04

    Here are two handy operators for canceling observable sequences. The difference between them is on what happens in case of cancellation. The TakeUntil causes a normal completion of the sequence (OnCompleted), while the WithCancellation causes an exceptional termination (OnError).

    /// Returns the elements from the source observable sequence until the
    /// CancellationToken is canceled.
    public static IObservable TakeUntil(
        this IObservable source, CancellationToken cancellationToken)
    {
        return source
            .TakeUntil(Observable.Create(observer =>
                cancellationToken.Register(() => observer.OnNext(default))));
    }
    
    /// Ties a CancellationToken to an observable sequence. In case of
    /// cancellation propagates an OperationCanceledException to the observer.
    public static IObservable WithCancellation(
        this IObservable source, CancellationToken cancellationToken)
    {
        return source
            .TakeUntil(Observable.Create(o => cancellationToken.Register(() =>
                o.OnError(new OperationCanceledException(cancellationToken)))));
    }
    

    Usage example:

    var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
    
    var pulses = Observable
        .Generate(0, i => true, i => i + 1, i => i, i => TimeSpan.FromMilliseconds(500))
        .WithCancellation(cts.Token);
    

提交回复
热议问题