I have a rxjs@6 BehaviorSubject source$
, I want get subvalue from source$
const source$ = new BehaviorSubject(someValue);
const subSource$ = source$.pipe(map(transform));
I expect the subSource$
also is a BehaviorSubject, but is not and How can I get the subSource$
is a BehaviorSubject ?
BehaviorSubject is a variant of a Subject which has a notion of the current value that it stores and emits to all new subscriptions. This current value is either the item most recently emitted by the source observable or a seed/default value if none has yet been emitted.
The BehaviorSubject There are two ways to get this last emited value. You can either get the value by accessing the . value property on the BehaviorSubject or you can subscribe to it. If you subscribe to it, the BehaviorSubject will directly emit the current value to the subscriber.
A BehaviorSubject holds one value (so we actually need to initialize a default value). When it is subscribed it emits that value immediately. A Subject on the other hand, does not hold a value.
When a BehaviorSubject is piped it uses an AnonymousSubject, just like a regular Subject does. The ability to call getValue() is therefore not carried down the chain. This was a decision by the community. I agree (as do some others) that it would be nice if the ability to get the value after piping existed, but alas that is not supported.
So you would need to do something like:
const source$ = new BehaviorSubject(value);
const published$ = new BehaviorSubject(value);
const subSource$ = source$.pipe(...operators, multicast(published$));
You could then call getValue() on published$ to retrieve the value after it has passed through your operators.
Note that you would need to either call connect() on the subSource$ (which would make it a "hot" observable) or use refCount().
That said, this isn't really the most rxjs-ish way of doing things. So unless you have a specific reason for dynamically retrieving the value after it passes through your operator vs just subscribing to it in the stream, maybe rethink the approach?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With