Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does piping a BehaviorSubject create an AnonymousSubject in RxJS?

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.

like image 710
Kevin Ghadyani Avatar asked Apr 24 '18 03:04

Kevin Ghadyani


People also ask

What is subject and BehaviorSubject in rxjs?

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.

Is a subject an Observable?

A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners. Every Subject is an Observable. Given a Subject, you can subscribe to it, providing an Observer, which will start receiving values normally.

What is the difference between BehaviorSubject vs observable?

Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities. An observable can be created from both Subject and BehaviorSubject using subject.

How does subject work in Angular?

A Subject is a special type of Observable that allows values to be multicasted to many Observers. The subjects are also observers because they can subscribe to another observable and get value from it, which it will multicast to all of its subscribers. Basically, a subject can act as both observable & an observer.


1 Answers

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
like image 66
Tal Ohana Avatar answered Nov 15 '22 14:11

Tal Ohana