Below is a code snippet of a component in my application where I subscribe to multiple observables and load data [an api call] after I get values respectively.
ngOnInit() {
this.combinedObservable$ = combineLatest(
this.service1.getStudentId(),
this.service2.getTeacherId(),
this.service3.getResultId(),
this.service4.getReportId(),
this.service5.getYearId(),
).subscribe(value => {
this.studentId = value[0];
this.teacherId = value[1];
this.resultId = value[2];
this.reportId = value[3];
this.yearId = value[4];
// Load Data for the page by making an api call
this.loadData(value[0], value[1], value[2], value[3], value[4]);
});
}
ngOnDestroy() {
this.combinedObservable$.unsubscribe();
}
CombineLatest works for me in this scenario, however the loadData is being called multiple times. I believe this is happening because of the observables emitting values after they update. The initial values for [studentId, teacherId, resultId, reportId, yearId] from the service are set to 0, to cater combineLatest.
Is there any way I can call LoadData method [api call] after all the 5 values are received [not the intialvalues of 0]? Something like onComplete?
repleace combineLatest
with forkJoin
which will wait for all observables complete before emits.