Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe Filter using Inner Observable Predicate

Tags:

rxjs

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.

like image 557
James B Avatar asked Nov 24 '25 19:11

James B


1 Answers

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

like image 99
kos Avatar answered Nov 28 '25 15:11

kos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!