How do you establish whether or not a method should return IEnumerable
or IObservable
?
Why would I choose one paradigm over t
Use IObservable
if you want to push data to callers of your method at your convenience. You do this by calling OnNext()
on Observers
that registered interest via Subscribe()
.
Use IEnumerable
if you want callers of your method to pull data at their convenience. They do this by calling GetEnumerator()
to acquire an IEnumerator
and calling MoveNext()
and Current
(foreach
compiles to this).
UPDATE: Perhaps best to give some examples:
A function that returns currency prices in a bank is a good candidate for IObservable
. Here the information is time-critical. As the server of this data, you need to get it to the client as soon as possible. The client won't know when that data is ready. So you push it to them.
A function that returns the valid trading days for a particular financial instrument and is used to populate the blackout days on a calendar control is a good candidate for IEnumerable. This data rarely changes and the client (setting up the control) prefers to consume it at a pace it dictates.