Home > Software design >  How to call second method only after first method returns observable?
How to call second method only after first method returns observable?

Time:03-10

buttonClicked() {
    let num = 0;
    this.myService.myFirstMethod().subscribe(response=> {
        num = response.result;
    });

    this.myService.mySecondMethod(num).subscribe(response=> {
        console.log(response);
    });        
}

How can I call the second method only when the first one is returned, chain them like .then in Promise?

CodePudding user response:

You can use switchMap


buttonClicked() {
    this.myService
        .myFirstMethod()
        .pipe(response => {
           const num = response.result;
           return this.myService.mySecondMethod(num)
        })
        .subscribe(response => {
            console.log(response);
        });        
}

CodePudding user response:

You can map an observable emission to another observable by using a "Higher order mapping operator" (switchMap, mergeMap, concatMap, exhaustMap).

If your myFirstMethod() only emits a single value, it doesn't really matter which one you use, let's us switchMap, for this example:

buttonClicked() {
    this.myService.myFirstMethod().pipe(
        switchMap(num => this.myService.mySecondMethod(num))
    ).subscribe(secondResponse => {
        console.log(secondResponse);
    });        
}

You pass a function that returns an observable to switchMap. This "inner observable" will be subscribed (and unsubscribed) to internally by switchMap. Emissions from the "inner observable" are then emitted. So, it essentially maps an emission from observable #1 to emissions from observable #2.

  • Related