Created
November 6, 2013 03:23
-
-
Save StephenCleary/7330384 to your computer and use it in GitHub Desktop.
ObserverProgress: An IProgress implementation that forwards to an IObserver.
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
using System; | |
using System.Threading.Tasks; | |
namespace Nito.AsyncEx | |
{ | |
/// <summary> | |
/// A progress implementation that sends progress reports to an observer stream. Optionally ends the stream when the task completes. | |
/// </summary> | |
/// <typeparam name="T">The type of progress value.</typeparam> | |
internal sealed class ObserverProgress<T> : IProgress<T> | |
{ | |
/// <summary> | |
/// The observer to pass progress reports to. | |
/// </summary> | |
private readonly IObserver<T> _observer; | |
/// <summary> | |
/// Initializes a new instance of the <see cref="ObserverProgress<T>"/> class. | |
/// </summary> | |
/// <param name="observer">The observer to pass progress reports to. May not be <c>null</c>.</param> | |
public ObserverProgress(IObserver<T> observer) | |
{ | |
_observer = observer; | |
} | |
void IProgress<T>.Report(T value) | |
{ | |
_observer.OnNext(value); | |
} | |
/// <summary> | |
/// Watches the task, and completes the observer (via <see cref="IObserver{T}.OnError"/> or <see cref="IObserver{T}.OnCompleted"/>) when the task completes. | |
/// </summary> | |
/// <param name="task">The task to watch. May not be <c>null</c>.</param> | |
public void ObserveTaskForCompletion(Task task) | |
{ | |
task.ContinueWith(_ => | |
{ | |
if (task.IsFaulted) | |
_observer.OnError(task.Exception.InnerException); | |
else | |
_observer.OnCompleted(); | |
}, TaskScheduler.Default); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sooo nice!