James B
James B

Reputation: 9605

Pipe Filter using Inner Observable Predicate

I'm trying to get my head around RxJS. In particular I have a situation where I'm attempting to pipe emissions from an outer observable through a filter that has an inner observable predicate that depends on the output of the outer observable. By way of example:

outerObs.pipe(
    filter(x => myPredicate(x))
).subcribe()

where mypredicate is a function that returns Observable<boolean>. Obviously the above does not work as the filter operator expects a boolean and not Observable<boolean>. Is there a nice pipeable way to do this? I've tried looking at the withLatestFrom and mergeMap operators, but nothing really seems to be working.

Upvotes: 3

Views: 428

Answers (1)

kos
kos

Reputation: 5364

You'll need to use one of the *Map operators: mergeMap, exhaustMap, switchMap or concatMap

Heres an example with concatMap that will guarantee initial order of emission:

outerObs.pipe(
  concatMap(x => myPredicate(x).pipe(
    filter(subx => subx == true), // filter by sub value
    mapTo(x)                      // map sub value back to outer value
  ))
).subcribe()

See this mergeMap vs exhaustMap vs switchMap vs concatMap comparison to pick the right one.

Hope this helps

Upvotes: 3

Related Questions