2

I have a function that request data from an API using subscriptions. I am trying to re-write it so that it returns a boolean when all API calls have finished. Is there a better way to write this?

My current code:

public res1=null;
public res2=null;

getData(){
 this.svc.getData1().subscribe(x={this.res1=x;})
 this.svc.getData2().subscribe(x={this.res2=x;})
}

I was thinking of trying to create an Observable that listens for changes to the nested subscriptions: (not tested code!)

getData(): Observable<boolean>{
 this.svc.getData1().subscribe(x=>{
   this.res1=x;
   this.svc.getData2().subscribe(x=>{this.res2=x; 
     return true;
   })
 })
)

}

Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • 1
    Possible duplicate of [How to check if multiple subscriptions reached onComplete()?](https://stackoverflow.com/questions/52316084/how-to-check-if-multiple-subscriptions-reached-oncomplete) – Harun Yilmaz May 30 '19 at 13:43
  • Also see: https://stackoverflow.com/search?q=%5Bangular%5D+multiple+subscriptions – Harun Yilmaz May 30 '19 at 13:43
  • Possible duplicate of [Angular Subscribe within Subscribe](https://stackoverflow.com/questions/55447803/angular-subscribe-within-subscribe) – wentjun May 30 '19 at 13:48

2 Answers2

1

One way of doing it would be to use combineLatest. Combine latest emits a value when all the observables have emitted one value.

combineLatest(observeable1$, observable2$).subscribe(
  // when both have submitted a value. return what you like.
);

If your observable are only going to resolve once. You can use forkJoin as well. Which is similar to promise.All

Muhammad Kamran
  • 978
  • 6
  • 10
0

you can use merge operator to combine observables and subscribe them in parallel.

 getData(): Observable<boolean>{
    let isCompleted: Observable<boolean>;
    merge(this.svc.getData1(), this.svc.getData2()).subscribe(
      (val) => {console.log(val) },
    (err) => { console.log(err) },
    ()=>{isCompleted = of (true); });
    return isCompleted;
  }
indrajeet
  • 837
  • 10
  • 17