How do I make http.get requests sequential?

As much as I respect @SigmundFroyd’s many contributions here, a couple of rules I try to follow in situations like these:

  • don’t subscribe to observables in the same place you create them
  • don’t nest subscriptions, maps or pipes

Following those leads us to this implementation, which should be pretty easily adapted to your real-world problem:

export class WombatService {
  // equivalent to list of playlists
  numbers(): Observable<number[]> {
    return of([2, 4, 6, 8])
      .pipe(delay(1200));
  }

  // transforms a single playlist ID to its associated video
  square(n: number): Observable<number> {
    return of(n*n)
      .pipe(delay(800));
  }

  // postprocesses the secondary response to mogrify it into whatever format you desire
  wombatify(n: number): string {
    return n + ' wombats';
  }

  // now weave it all together
  wombats(): Observable<string[]> {
    return this.numbers().pipe(
      mergeMap(ns => forkJoin(ns.map(n => this.square(n)))),
      map(sqs => sqs.map(sq => this.wombatify(sq)))
    );
  }
}

export class HomePage {
  wombats: string[] = [];

  constructor(wombatsvc: WombatService) {
    wombatsvc.wombats().subscribe(wombats => this.wombats = wombats);
  }
}

<ion-list>
  <ion-item *ngFor="let wombat of wombats">
    <ion-label>{{wombat}}</ion-label>
  </ion-item>
</ion-list>
1 Like