I just want to wait for all concurrent HTTP calls completed then make another HTTP request.
here is my code ...
const observable = requestData.map(x => this.blobService.addNewVideo(x.uniqueName, x.chunk, x.base64BlockId));
from(observable).pipe(mergeAll(5)).subscribe(
(event: HttpEvent<any>)=>{
switch (event.type) {
case HttpEventType.UploadProgress:
this.progress = Math.round((event.loaded / event.total!) * 100);
console.log(`uploaded! ${this.progress}%`);
break;
case HttpEventType.Response:
console.log('Successfully uploaded',event.body,' : ',event.status,event.statusText);
}
}
);
here are successfully uploaded all the chunks but the problem is that I am unable to wait for all requests completed to make another HTTP request. how can I do that?
Thanks in advance
CodePudding user response:
if you want to wait for all the request to complete, you should use forkJoin
and the you can use concatMap
for the next request.
https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin
CodePudding user response:
You can use forkJoin
in order to wait for an array of observables to complete and return the observables containing all results. After that you can use switchMap
in order to "switch" to the final call you want to make. The subscription will then contain the result of the last call.
Note:
- In order to perform side effects (like setting the loading progress) you should use
tap
operator - You should rework your approach about setting the
progress
, since you currently have only a single value. Unfortunately you have an array of requests, where you probably want to set the progress for each call individually. Now all observables would simply write to the sameprogress
variable resulting inprogress
containing only the actual progress of the last emitted event.
const requests = requestData.map((x) =>
this.blobService.addNewVideo(x.uniqueName, x.chunk, x.base64BlockId).pipe(
tap((event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.UploadProgress:
this.progress = Math.round((event.loaded / event.total!) * 100);
console.log(`uploaded! ${this.progress}%`);
break;
case HttpEventType.Response:
console.log(
'Successfully uploaded',
event.body,
' : ',
event.status,
event.statusText
);
}
})
)
);
forkJoin(requests)
.pipe(
switchMap(
(results) => null //here you can return the finall call.
)
)
.subscribe(
(res) => console.log(res) //result of last call
);
}