How to merge two subjects and return a new stream?

Issue

I have two subjects:

public triggger$ = new BehaviorSubject<boolean>(true);
public id$ = new BehaviorSubject<number>([]);
public objects$ = new BehaviorSubject<Map<number, Item[]>>(null);

I want to subscribe to the triggger$ then to id$ then get objects$ and find all id inside objects and return it in a new array?

How to merge these subjects?

Solution

Confused

Your code:

You shouldn’t use BehaviorSubject if you don’t have a reasonable default.

// Okay good. true is a boolean
public triggger$ = new BehaviorSubject<boolean>(true);
// What is this? [] is not a number. 
public id$ = new BehaviorSubject<number>([]);
// What is this? Null  is not a Map.
public objects$ = new BehaviorSubject<Map<number, Item[]>>(null);

Your question:

It’s not really clear what you want to do. I’ll try to interpret what you’ve written, it’s just a guess.

My attempt

What this does:

  • Start with trigger$
  • when trigger$ emits true, subscribe to id$
  • Use number from id$ to get item[] from map
public mergedSubjects$ = this.triggger$.pipe(
  switchMap(bool => bool? this.id$ : EMPTY),
  switchMap((id: number) => this.objects$.pipe(
    map(dict => dict.get(id))
  ))
);

Answered By – Mrk Sef

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published