Bagusflyer
Bagusflyer

Reputation: 12925

Angular 2 promise/observable chain two events?

I'm wondering if observable or promise can be used in the following use case in angular 2:

There are two asynchronized upload tasks. I'd like to know how I can detect both tasks are finished.

My upload task (implemented in promise but it's easily be changed to observable if needed) is like this:

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

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

How to chain these two events together in either promise or observable so that I know both tasks are finished? Thanks

Upvotes: 5

Views: 9360

Answers (4)

Felix Livni
Felix Livni

Reputation: 1244

You can use Promise.all which returns a new Promise that resolves when all of the promises in the argument array have resolved.

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

Note, if your myService.upload method returned a Promise, rather than Promise, you could access the return values this way:

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

Upvotes: 2

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658225

complete is executed when all the source stream are closed.

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

if you want to set a max number of results to wait for

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

Upvotes: 5

Sasxa
Sasxa

Reputation: 41314

You can use one of the Combining 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 accepts one item emitted by each of those Observables or resolved by those Promises as input and produces a single item to be emitted by the resulting Observable.

Upvotes: 7

Michael Kang
Michael Kang

Reputation: 52867

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

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

Upvotes: 7

Related Questions