1

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?

user1375481
  • 309
  • 1
  • 8
  • 19

1 Answers1

4

repleace combineLatest with forkJoin which will wait for all observables complete before emits.

Yuchao Wu
  • 383
  • 2
  • 8
  • 2
    This is true. But `forkJoin(this.a(), this.b(), this.c)()` is now deprecated in favour of `forkJoin([this.a(), this.b(), this.c()])`. And even better, you can do `forkJoin({ a: this.a(), b: this.b(), c: this.c() }).subscribe(result => console.log(result.a);)` – Kurt Hamilton Mar 02 '20 at 07:05