Given an Observable that will start pushing events once Subscribe is called. How can the sequence be converted into an IEnumerable.
In 2010 Jon Skeet wrote about his first impressions of RX and wrote this, which would be equivalent to what I need.
public static List<T> ToList<T>(this IObservable<T> source)
{
List<T> ret = new List<T>();
source.Subscribe(x => ret.Add(x));
return ret;
}
https://codeblog.jonskeet.uk/2010/01/16/first-encounters-with-reactive-extensions/
While this solution would work it seems like there should be a better way.
What we're really interested in is the ability to await the observable in a way that behaves similarly to Subscribe.
await observable.ToList()
However, this doesn't seem to work for me.
I've also looked into these two methods
observable.ToEnumerable
observable.Next
A little more information
I plan to use this to write some unit tests.
- I'm using a
ReplaySubjectand performing a sequence of actions with a test substitute. - Calls to the substitute are recorded via
OnNext. - I can get the list of calls and Assert they are correct.
async/awaitwere two years in the future. By 2011 Observable had its ownToList()extension method - Panagiotis KanavosIObservable<IList<TSource>> ToList<TSource>(this IObservable<TSource> source)MSDN And Daniel is asking about IObservable<T> to IEnumerable<T> conversion - lerthe61ToEnumerable()offers a blocking alternative. Jon Skeet's article was written back when Rx was a research project and doesn't apply anymore - Panagiotis Kanavos