Search code examples
angularfilterrxjsobservablesubject

Is this the right way to filter a BehaviorSubject<object[]> with a another BehaviorSubject?


I've been wondering around for hours on the web on how to filter a BehaviorSubject with a another BehaviorSubject and heard of switchMap so I implemented it. It works but, I wonder if there is a more proper way of doing it. TIA.

// results$:arrayOfObject and activeEntityFilter$:number are both BehaviorSubjects
results$ = this.flowService.searchAppResult$;

filteredResult$ = this.activeEntityFilter$.pipe(
  switchMap((activeEntityFilter) =>
    this.results$.pipe(
      map((flows) => {
        return flows.filter((flow: any) => {
          return activeEntityFilter
            ? flow.initiator_id == activeEntityFilter
            : true;
        });
      })
    )
  )
);

Solution

  • You can use combineLatest

    The flow will be triggered when one of the observables emits new value.

    results$ = this.flowService.searchAppResult$;
    
    filteredResult$ = combineLatest(this.activeEntityFilter$, results$).pipe(
                            map(([activeEntityFilter, results]) => {
                                return results.filter((result: any) => {
                                    return activeEntityFilter
                                        ? result.initiator_id == activeEntityFilter
                                        : true;
                                });
                            })
                        );