When to use IEnumerable vs IObservable?

前端 未结 4 1467
情话喂你
情话喂你 2021-02-04 05:24

How do you establish whether or not a method should return IEnumerable or IObservable?

Why would I choose one paradigm over t

4条回答
  •  心在旅途
    2021-02-04 06:18

    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.

提交回复
热议问题