I'm in a situation where I have a list of Tasks that I'm working through (enable drive, change position, wait for stop, disable).
The 'wait for' monitors an IObservable<Status>, which I want to wait on (so I can thread it through ContinueWith and the other tasks).
I started out with the following tasks inside the OnNext handling of the subscriber, but that was just ugly. What I've now come up with is this extension method:
public static Task<T> WaitFor<T>(this IObservable<T> source, Func<T, bool> pred)
{
var tcs = new TaskCompletionSource<T>();
source
.Where(pred)
.DistinctUntilChanged()
.Take(1) //OnCompletes the observable, subscription will self-dispose
.Subscribe(val => tcs.TrySetResult(val),
ex => tcs.TrySetException(ex),
() => tcs.TrySetCanceled());
return tcs.Task;
}
(UPDATED with svick's suggestion of handling OnCompleted and OnError)
Questions:
- Is this good, bad, or ugly?
- Did I miss an existing extension which could have done this?
- Are the
WhereandDistinctUntilChangedin the right order? (I think they are)