What do the various ISubject implementations do and when would they be used?

前端 未结 4 1364
梦谈多话
梦谈多话 2021-01-31 09:19

I have a fairly good idea of what the Subject class does and when to use it, but I\'ve just been looking through the language reference on msdn and see there are various other I

4条回答
  •  野的像风
    2021-01-31 10:21

    These subjects all share a common property - they take some (or all) of what gets posted to them via OnNext and record it and play it back to you - i.e. they take a Hot Observable and make it Cold. This means, that if you Subscribe to any of these more than once (i.e. Subscribe => Unsubscribe => Subscribe again), you'll see at least one of the same value again.

    ReplaySubject: Every time you subscribe to the Subject, you get the entire history of what has been posted replayed back to you, as fast as possible (or a subset, like the last n items)

    AsyncSubject: Always plays back the last item posted and completes, but only after the source has completed. This Subject is awesome for async functions, since you can write them without worrying about race conditions: even if someone Subscribes after the async method completes, they get the result.

    BehaviorSubject: Kind of like ReplaySubject but with a buffer of one, so you always get the last thing that was posted. You also can provide an initial value. Always provides one item instantly on Subscribe.

提交回复
热议问题