Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BehaviorSubject map a BehaviorSubject

Tags:

rxjs

rxjs6

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 ?

like image 517
quanwei li Avatar asked Jul 09 '18 10:07

quanwei li


People also ask

What 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.

Can you subscribe to a behavior subject?

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.

What is difference between subject and BehaviorSubject?

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.


1 Answers

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?

like image 77
Josh Avatar answered Sep 19 '22 01:09

Josh