When to use IEnumerable vs IObservable?

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

    Types

    • IEnumerable
      • You repeatedly "pull" from a sequence of T's
    • IObservable
      • 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>

    • You are running an HTTP web server: IObservable

    • You want to do get the nodes of a tree data structure in a breadth-first manner: IEnumerable

    • You are responding to user interface button clicks: IObservable

    In each of these examples (especially the IObservable cases), it just wouldn't make sense to use the other type.

    But what if I want to use the "other" type...

    IObservable to IEnumerable

    If something is naturally an IObservable but you want to process it as if it were an IEnumerable, you can do that with this method:

    IEnumerable Observable.ToEnumerable(this IObservable)
    
    • When a T gets "pushed" by the IObservable, it gets sent into a queue.
    • When you try to "pull" a T out of the IEnumerable, it blocks until the queue isn't empty, then dequeues.

    IEnumerable to IObservable

    If something is naturally an IEnumerable but you want to process it as if it were an IObservable, you can do that with this method:

    IObservable Observable.ToObservable(this IEnumerable)
    
    • A thread from the .NET thread pool will repeatedly try to "pull" a T from the IEnumerable.
    • Each time it "pulls" a T, it "pushes" it at you via the IObservable.

提交回复
热议问题