When to use IEnumerable vs IObservable?

前端 未结 4 1416
情话喂你
情话喂你 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:14

    IObservable is a specialized interface that can be used for pub/sub and various other patterns. You would know when you needed to return an IObservable, so if there is not specific need then return IEnumerable.

    Update to question in comment

    Basically, IObservable<> uses a "Push" mechanism and IEnumerable<> uses a "Pull" mechanism. If you are going to simply obtain a list of data that doesn't need to notify subscribers of changes (push) then you can use IEnumerable. If a subscriber (Window, Control, other Client programs/routines, etc...) needs to know when data changed then use IObservable<>. One example is using IObservable to update the main UI thread in a windows program from a child thread (Normally this cannot be done without fancy footwork. Read up on .NET Reactive Extensions (Rx.NET).

提交回复
热议问题