2

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.

Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
David Dahan
  • 10,576
  • 11
  • 64
  • 137

1 Answers1

2

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)
  })
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
  • Wow thanks it's very interesting! One problem: Currently, if one of both requests fails, the whole thing fails. How to do if I want to call my method if at least one of both requests is successful? – David Dahan Aug 26 '17 at 15:25
  • Sorry, no idea. Probably the best bet to ask a new question. – Lazar Ljubenović Aug 26 '17 at 16:05