How to get the “current” value of an Observer at subscribe-time

后端 未结 1 1362
挽巷
挽巷 2021-01-30 08:59

I\'m having a hard time grokking one particular part of RxJs: when you subscribe to an Observable, you\'re only subscribing to any future events from that Stream. Compa

相关标签:
1条回答
  • 2021-01-30 09:19

    Rx offers both behaviors (as well as others).

    The different Rx Subjects available can let you explore the different ways observables can behave:

    • the Rx.Subject is the most basic fire-and-forget variety -- if you were not subscribed when the event happened, then you do not see it.

    • Use new Rx.BehaviorSubject(undefined) instead of Subject and you get the behavior you were looking for, since a BehaviorSubject represents a "value that can change"

    • Use new Rx.ReplaySubject(5) and you'll get the 5 most recent values as soon as you subscribe

    • Use new Rx.AsyncSubject() and you will get nothing until the observable completes at which time you will get the final value (and continue to get the final value if you subscribe again). This is the true Rx analog of Promises, since it produces nothing until it "resolves" (i.e. completes), and afterwards always gives the value to anyone that subscribes.

    0 讨论(0)
提交回复
热议问题