简体   繁体   中英

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

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.

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];
});

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: () => { ... });

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) => {
  // ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM