Reputation: 12925
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
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
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
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
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