Search code examples
rxjsreactive-extensions-js

Ionic2/angular: how to know when 2 different observables are terminated?


Kind of beginner question here: in an Ionic2 component, I have 2 different service calls using Observables:

  getTimelineEvents() {
    this.receiptsEventsRequestState = RequestState.Pending;
    this.chargesEventsRequestState = RequestState.Pending;

    this.miscService.getCustomerReceiptsEvents()
      .subscribe(
        (events: TimelineEvent[]) => {
         this.receiptsEventsRequestState = RequestState.Success;
         this.receiptsEvents = events;
         },
      );

    this.miscService.getCustomerChargesEvents()
      .subscribe(
        (events: TimelineEvent[]) => {
        this.chargesEventsRequestState = RequestState.Success;}
        this.chargesEvents = events;
      );

  }

I'd like to know when both getCustomerReceiptsEvents and getCustomerChargesEvents are successful sothat I can call another method (this method needs chargesEvents and receiptsEvents data).

Thanks.


Solution

  • You can wait for both observables to complete and get the values they emitted by using the forkJoin operator. They will still be executed in parallel.

    Observable.forkJoin(
      this.miscService.getCustomerReceiptsEvents(),
      this.miscService.getCustomerChargesEvents(),
    )
      .subscribe(([receipts, charges] => {
        console.log('Results', receipts, charges)
      })