Angular 2 promises / observable chain of two events?

I am wondering if one can use observable or promise in the following usage example in angular 2:

There are two tasks of asynchronous loading. I would like to know how I can determine that both tasks are complete.

My download task (implemented in the promise , but it can easily be changed to observable if necessary):

myService.upload('upload1').then(() => { }) myService.upload('upload2').then(() => { }) 

How to connect these two events together in a promise or observable so that I know that both tasks are completed? Thanks

+5
source share
4 answers

complete is executed when all source threads are closed.

 Rx.Observable.merge( myService.upload('upload1'), myService.upload('upload2').subscribe({complete: () => { ... }); 

if you want to set the maximum number of results to wait

 Rx.Observable.merge( myService.upload('upload1'), myService.upload('upload2') .take(2) .subscribe({complete: () => { ... }); 
+5
source

You can use one of the combination of operators with observables. Observable.zip() , for example, works with promises ...

 Observable.zip( first, second, function (firstResolvedValue, secondResolvedValue) { return firstResolvedValue && secondResolvedValue; } ) 

zip accepts a variable number of Observables or Promises as parameters, followed by a function that takes one element emitted by each of these Observables or allowed by these Promises as input, and produces one element that must be issued based on the received Observable.

+7
source

Use forkJoin , which is equivalent to $ q.all from Angular 1.x (a and b are observable):

 Rx.Observable.forkJoin([a,b]).subscribe(t=> { var firstResult = t[0]; var secondResult = t[1]; }); 
+7
source

You can use Promise.all, which returns a new promise that resolves when all promises in the argument array are resolved.

 Promise.all([myService.upload('upload1'), myService.upload('upload2')]).then(() => { // ... }); 

Note that if your myService.upload method returned Promise rather than Promise, you could get the return values โ€‹โ€‹as follows:

 Promise.all([myService.upload('upload1'), myService.upload('upload2')]) .then((retValue1, retValue2) => { // ... }); 
+2
source

Source: https://habr.com/ru/post/1243029/


All Articles