quanwei li
quanwei li

Reputation: 359

BehaviorSubject map a BehaviorSubject

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 ?

Upvotes: 13

Views: 7288

Answers (1)

Josh
Josh

Reputation: 111

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?

Upvotes: 4

Related Questions