How do you establish whether or not a method should return IEnumerable
or IObservable
?
Why would I choose one paradigm over t
IEnumerable
T
'sIObservable
T
's is being "pushed" at youWhy would I choose one paradigm over the other?
You typically don't "choose" one paradigm over the other. Usually one stands out naturally as the correct choice, with the other one not making any sense.
Consider the following examples:
A huge CSV text file has an item on each line, and you want to process them one at a time without loading the entire file into memory at once: IEnumerable
>
You are running an HTTP web server: IObservable
You want to do get the nodes of a tree data structure in a breadth-first manner: IEnumerable
You are responding to user interface button clicks: IObservable
In each of these examples (especially the IObservable
cases), it just wouldn't make sense to use the other type.
IObservable
to IEnumerable
If something is naturally an IObservable
but you want to process it as if it were an IEnumerable
, you can do that with this method:
IEnumerable Observable.ToEnumerable(this IObservable)
T
gets "pushed" by the IObservable
, it gets sent into a queue.T
out of the IEnumerable
, it blocks until the queue isn't empty, then dequeues.IEnumerable
to IObservable
If something is naturally an IEnumerable
but you want to process it as if it were an IObservable
, you can do that with this method:
IObservable Observable.ToObservable(this IEnumerable)
T
from the IEnumerable
.T
, it "pushes" it at you via the IObservable
.