12

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 ?

quanwei li
  • 354
  • 2
  • 16
  • Why do you expect it to be a subject and how would it behave? – a better oliver Jul 09 '18 at 11:15
  • 1
    I using https://github.com/facebook/react/tree/master/packages/create-subscription for react. there need behaviorsubject as props. I want split to subvalue behaviorsubject to difference component. – quanwei li Jul 09 '18 at 11:17

1 Answers1

3

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?

Josh
  • 101
  • 5