Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use IEnumerable vs IObservable?

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?

like image 378
jmcg Avatar asked Jun 13 '13 08:06

jmcg


People also ask

Why to use IEnumerable instead of List?

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.

Is IEnumerable faster than List C#?

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.

Is observable collection an IEnumerable?

Note that ObservableCollection implements IEnumerable , among other interfaces.


1 Answers

Types

  • IEnumerable<T>
    • You repeatedly "pull" from a sequence of T's
  • IObservable<T>
    • A sequence of T's is being "pushed" at you

Why 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.

Examples

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.

But what if I want 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>)
  • When a T gets "pushed" by the IObservable<T>, it gets sent into a queue.
  • When you try to "pull" a 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>)
  • A thread from the .NET thread pool will repeatedly try to "pull" a T from the IEnumerable<T>.
  • Each time it "pulls" a T, it "pushes" it at you via the IObservable<T>.
like image 197
Timothy Shields Avatar answered Sep 19 '22 16:09

Timothy Shields