Skip to content

Instantly share code, notes, and snippets.

@StephenCleary
Created November 6, 2013 03:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephenCleary/7330384 to your computer and use it in GitHub Desktop.
Save StephenCleary/7330384 to your computer and use it in GitHub Desktop.
ObserverProgress: An IProgress implementation that forwards to an IObserver.
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&lt;T&gt;"/> 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);
}
}
}
@SuperJMN
Copy link

Sooo nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment