I'm writing an application that will monitor the current build number of all of our applications across different servers. This is done by making an http request to a txt file in every application. I'm doing that using a foreach loop.
The issue I'm having is that I'm not sure how (using Observables) to know when all of the requests are finished.
As the requests come back, I add the response as a property of an array of objects. Then once I have all of the data, I bind it to the component's template, where it gets filtered by a Pipe. As such, I need to make sure I don't bind it until all of the data is finished coming down.
Here is how I'm getting the data:
this.apps.forEach(app => {
app.Environments.forEach(env => {
this._buildMonitorService.getBuilds(env.URL)
.subscribe((data) => {
setupBuilds(this.apps,data.url,data._body);
});
});
});
setupBuilds
adds the response to my array of applications.
The thing I'm looking for is effectively a Promise.all
where I'll bind
this.builds
to the data setup in setupBuilds
but I don't know how to do that with rxjs observables
Observable.forkJoin
is the equivalent to Promise.all
but for observables.
Here is a sample:
Here is the way you could refactor your code:
var observables = [];
this.apps.forEach(app => {
app.Environments.forEach(env => {
observables.push(this._buildMonitorService.getBuilds(env.URL));
});
});
Observable.forkJoin(observables).subscribe(
(result) => {
result.forEach((data) => {
setupBuilds(this.apps,data.url,data._body);
});
}
);
This way you will be sure that all requests were executed when the callback registered in the subscribe method is called...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With