I have a very simple IObservable that acts as a pulse generator every 500ms:
var pulses = Observable.GenerateWithTime(0, i => true
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);