Created
December 15, 2016 15:17
-
-
Save GeorgeTsiokos/bceb7387f6e898703e8516f8fcccac03 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class CancellationTokenExtensions { | |
/// <summary> | |
/// Creates an observable sequence from a cancellationToken | |
/// </summary> | |
/// <param name="cancellationToken">token to observe</param> | |
/// <param name="throwOperationCanceledException">true to terminate the sequence with an exception instead of emitting a value</param> | |
/// <returns>an observable sequence that emits a value when the token is fired</returns> | |
public static IObservable<Unit> ToObservable (this CancellationToken cancellationToken, bool throwOperationCanceledException = false) { | |
if (!cancellationToken.CanBeCanceled) { | |
return Observable.Never<Unit> (); | |
} | |
Func<IObserver<Unit>, IDisposable> subscribe; | |
if (throwOperationCanceledException) { | |
subscribe = observer => cancellationToken.Register (() => observer.OnError (new OperationCanceledException (cancellationToken))); | |
} | |
else { | |
subscribe = observer => cancellationToken.Register (() => { | |
observer.OnNext (Unit.Default); | |
observer.OnCompleted (); | |
}); | |
} | |
return Observable.Create (subscribe); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment