How do you establish whether or not a method should return IEnumerable<T>
or IObservable<T>
?
Why would I choose one paradigm over the other?
We aren't forcing the caller to convert their data structure to a List unnecessarily. So it isn't that IEnumerable<T> is more efficient than list in a "performance" or "runtime" aspect. It's that IEnumerable<T> is a more efficient design construct because it's a more specific indication of what your design requires.
IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.
Note that ObservableCollection implements IEnumerable , among other interfaces.
IEnumerable<T>
T
'sIObservable<T>
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<List<string>>
You are running an HTTP web server: IObservable<WebRequest>
You want to do get the nodes of a tree data structure in a breadth-first manner: IEnumerable<Node>
You are responding to user interface button clicks: IObservable<Click>
In each of these examples (especially the IObservable<T>
cases), it just wouldn't make sense to use the other type.
IObservable<T>
to IEnumerable<T>
If something is naturally an IObservable<T>
but you want to process it as if it were an IEnumerable<T>
, you can do that with this method:
IEnumerable<T> Observable.ToEnumerable(this IObservable<T>)
T
gets "pushed" by the IObservable<T>
, it gets sent into a queue.T
out of the IEnumerable<T>
, it blocks until the queue isn't empty, then dequeues.IEnumerable<T>
to IObservable<T>
If something is naturally an IEnumerable<T>
but you want to process it as if it were an IObservable<T>
, you can do that with this method:
IObservable<T> Observable.ToObservable(this IEnumerable<T>)
T
from the IEnumerable<T>
.T
, it "pushes" it at you via the IObservable<T>
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With