14

When creating an RxJS BehaviorSubject, it stays a BehaviorSubject until it's pipe'd. As soon a pipe'd version is returned, it becomes an AnonymousSubject.

Examples:

// Instance of `BehaviorSubject`
const behaviorSubject$ = new BehaviorSubject({ someValue: null })

// Suddenly becomes an Anonymous Subject
const anonymousSubject$ = (
    behaviorSubject$
    .pipe(
        pluck('someValue')
    )
)

// Also suddenly becomes an Anonymous Subject
const anonymousSubject$ = (
    new BehaviorSubject({ someValue: null })
    .pipe(
        pluck('someValue')
    )
)

I experience this same issue with ReplaySubject as well. I can't seem to pipe through the subject and return that subject back. It always converts to an AnonymousSubject. I think what I'm looking for here is Promise-like behavior where I can subscribe to this observable from anywhere and grab the one value passed into it.

Kevin Ghadyani
  • 6,829
  • 6
  • 44
  • 62
  • 1
    Do you have code that cares? If you do you shouldn't. – Aluan Haddad Apr 24 '18 at 03:58
  • I need to do `behaviorSubject$.value`. Should I be using a `ReplaySubject` instead? – Kevin Ghadyani Apr 24 '18 at 03:59
  • You need to pass an argument to BehaviorSubject() – siva636 Apr 24 '18 at 04:01
  • Why do you need the `value` from the result returned from `pipe` though? – Aluan Haddad Apr 24 '18 at 04:01
  • 1
    IMO using `value` is a code smell and even if `lift` returned a `BehaviorSubject`, what would you expect the `value` if the lifted subject to be? The original value or the plucked value? I think you should seriously reconsider using `value`. – cartant Apr 24 '18 at 04:43
  • Changed my example to show I'm passing a value. Also, I don't have to use `.value`, but even if I use a `ReplaySubject` instead, it converts to an `AnonymousSubject`, and I lose the value I passed. – Kevin Ghadyani Apr 24 '18 at 16:35
  • A pipe essentially returns an observer|observable combo (also called a Subject...) which emits values based on its source upon subscription. I don't see why the observer type matters. All you need to know is that you can subscribe to this observer to receive it values after all operators are processed – Jeffrey Devloo Dec 18 '19 at 19:32
  • 1
    `BehaviorSubject` allows you to do `subject.value`. I can't do that with `AnonymousSubject`. – Kevin Ghadyani Dec 18 '19 at 19:46

1 Answers1

9

This is happening due to lift called on Subject.

Let's take a deeper look at your example:

  1. You are instantiating a BehaviorSubject which extends Subject
  2. You are calling pluck operator which internally calls map operator
  3. map operator internally calls lift on BehaviorSubject which is delegated to Subject which then returns an AnonymousSubject
Tal Ohana
  • 1,128
  • 8
  • 15