brightpants
brightpants

Reputation: 525

RxJs: Filter content in observable using emission of another observable

I have an Observable<Project> that returns an array of objects. I need to filter this array based on an Observable<boolean> constructed from a request using the ids of the objects.

Something in the lines of the code below, but I need the actual objects at the array, not the array of booleans I currently mapped them too. I guess something in the lines of a zip that I could use after the initial observable has emmited to join both values so I can use them in the filter.

    this.projectService.getCurrentUserProjects().pipe(
      mergeAll(),
      mergeMap((project) => this.getProjectConditions(project.id)),
      filter((condition) => condition),
      toArray()
    )

My current leads here are:

  1. A way for me to access the values emmited by the mergeAll after the filter layer, for me to collect it into the array.
  2. A way for me to do a concatMap that returns an observable with both values so I can use it at the filter layer.
  3. Some sort of filter operator that takes in an Observable.

Upvotes: 0

Views: 284

Answers (1)

Rafi Henig
Rafi Henig

Reputation: 6424

Consider having an inner map returning both values (Data & Condition) as an array, as demonstrated below:

this.projectService.getCurrentUserProjects().pipe(
  mergeAll(),
  mergeMap((project) => this.getProjectConditions(project.id).pipe(map(condition => [project, condition]))),
  filter(([,condition]) => condition), // <= only destruct second parameter 
  map(([project]) => project), // <= only destruct first parameter 
  toArray()
)

Upvotes: 2

Related Questions