Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs One Observable Feeding into Another

I have a rather clunky looking set of code where the data from one observable is feed into another, like such:

let source = this.myService.getFoo()    .subscribe(result => {       let source2 = this.myService.getMoo(result)          .subscribe(result2 => { // do stuff });    }); 

I know that there are ways to combine and chain but I need data from source to be feed into source2. The nesting of subscribes looks terrible and I'm pretty certain there is a better way to do this.

Thanks!

like image 949
Siegmund Nagel Avatar asked Jun 16 '17 16:06

Siegmund Nagel


People also ask

How do you assign one Observable to another?

For transforming items emitted by an Observable into another Observable, you probably want to use the flatMap operator. It creates an inner Observable and flats its result to the outer stream. const source = this. myService .

How do you call one Observable after another?

Make a single observable out of the several ones that need to be executed in parallel (i.e. the many deletions), using forkJoin. Use switchMap to execute one observable after another.

What is FlatMap in RXJS?

The FlatMap operator transforms an Observable by applying a function that you specify to each item emitted by the source Observable, where that function returns an Observable that itself emits items. FlatMap then merges the emissions of these resulting Observables, emitting these merged results as its own sequence.

How do I use concatMap?

To use concatMap in Angular first we need to import it our Component or Service. import { concatMap } from 'rxjs/operators'; In the following code, we have two observables srcObservable which emits 1,2,3,4 & innerObservable which emits 'A','B','C','D' . The ConcatMap receives its values from the srcObservable .


1 Answers

For transforming items emitted by an Observable into another Observable, you probably want to use the flatMap operator. It creates an inner Observable and flats its result to the outer stream.

const source = this.myService     .getFoo()     .pipe(         flatMap(result => this.myService.getMoo(result))      )     .subscribe(result2 => {         // do some stuff     }); 

Here are some flat operators you can use that behave differently:

  • flatMap/mergeMap - creates an Observable immediately for any source item, all previous Observables are kept alive
  • concatMap - waits for the previous Observable to complete before creating the next one
  • switchMap - for any source item, completes the previous Observable and immediately creates the next one
  • exhaustMap - map to inner observable, ignore other values until that observable completes
like image 76
ZahiC Avatar answered Sep 30 '22 03:09

ZahiC