Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  39] [ 7]  / answers: 1 / hits: 42974  / 7 Years ago, fri, june 16, 2017, 12:00:00

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!


More From » rxjs

 Answers
5

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


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

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



  • mergeMap - creates an Observable immediately for any source item, all previous Observables are kept alive. (this was formerly known as flatMap).

  • 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


[#57427] Wednesday, June 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tylerdamiena

Total Points: 139
Total Questions: 90
Total Answers: 118

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
tylerdamiena questions
;