Why does piping a BehaviorSubject create an AnonymousSubject in RxJS?
Asked Answered
A

1

15

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.

Asclepiadaceous answered 24/4, 2018 at 3:53 Comment(8)
Do you have code that cares? If you do you shouldn't.Conium
I need to do behaviorSubject$.value. Should I be using a ReplaySubject instead?Asclepiadaceous
You need to pass an argument to BehaviorSubject()Offprint
Why do you need the value from the result returned from pipe though?Conium
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.Podgy
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.Asclepiadaceous
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 processedEarsplitting
BehaviorSubject allows you to do subject.value. I can't do that with AnonymousSubject.Asclepiadaceous
T
10

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
Tishatishri answered 10/1, 2020 at 9:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.