How to get current value of RxJS Subject or Observable?
The only way you should be getting values "out of" an Observable/Subject is with subscribe!
If you're using getValue()
you're doing something imperative in declarative paradigm. It's there as an escape hatch, but 99.9% of the time you should NOT use getValue()
. There are a few interesting things that getValue()
will do: It will throw an error if the subject has been unsubscribed, it will prevent you from getting a value if the subject is dead because it's errored, etc. But, again, it's there as an escape hatch for rare circumstances.
There are several ways of getting the latest value from a Subject or Observable in a "Rx-y" way:
- Using
BehaviorSubject
: But actually subscribing to it. When you first subscribe toBehaviorSubject
it will synchronously send the previous value it received or was initialized with. - Using a
ReplaySubject(N)
: This will cacheN
values and replay them to new subscribers. A.withLatestFrom(B)
: Use this operator to get the most recent value from observableB
when observableA
emits. Will give you both values in an array[a, b]
.A.combineLatest(B)
: Use this operator to get the most recent values fromA
andB
every time eitherA
orB
emits. Will give you both values in an array.shareReplay()
: Makes an Observable multicast through aReplaySubject
, but allows you to retry the observable on error. (Basically it gives you that promise-y caching behavior).publishReplay()
,publishBehavior(initialValue)
,multicast(subject: BehaviorSubject | ReplaySubject)
, etc: Other operators that leverageBehaviorSubject
andReplaySubject
. Different flavors of the same thing, they basically multicast the source observable by funneling all notifications through a subject. You need to callconnect()
to subscribe to the source with the subject.
A Subject
or Observable
doesn't have a current value. When a value is emitted, it is passed to subscribers and the Observable
is done with it.
If you want to have a current value, use BehaviorSubject
which is designed for exactly that purpose. BehaviorSubject
keeps the last emitted value and emits it immediately to new subscribers.
It also has a method getValue()
to get the current value.