Search code examples
rxjsrxjs-pipeable-operators

Take a subscribed result and immediate apply it to another subscription


Using RxJS, I have a situation where I need to retrieve a single value from an Observable and then immediately apply it to a separate subscription using pluck().

I have a workable solution, but it is inelegant. Is there a way to simplify or improve the process?

this.fooService.singleValue$.subscribe(value => {
   this.barService.allResults$.pipe(pluck(value)).subscribe(pluckedResult => {
       // do something with the plucked result
   });
});

Solution

  • Nested subscriptions aren't recommended way of doing things (i.e. using explicit subscription). Its better to use switchMap/concatMap/mergeMap operators in these types of situations, so you would not need to subscribe twice, but do it just once.

    this.fooService.singleValue$.pipe(switchMap((value => {
                        return this.barService.allResults$.pipe(pluck(value));
                    }))).subscribe(() => {
                        //do something
                    });