Search code examples
angulartypescriptrxjsrequest-queueing

RxJs chaining observables with subscriptions


I have a form which consists of blocks which are retrieved by calls to API.

I need to process each call accordingly to that specific call (I'm creating a formGroup part based on that call).

What I want is to have some kind of global observable/status which will be completed when all calls are made and processed.

Now I'm doing it by creating a BehaviorSubject counter and on each request I increment this. When this counter reaches some value I change loading to false and show a form then. Is there a better way?

It looks like

o1.subscribe(() => {... this.counter.next(this.counter.value + 1) });
o2.subscribe(() => {... this.counter.next(this.counter.value + 1) });
o3.subscribe(() => {... this.counter.next(this.counter.value + 1) });

.

this.counter.subscribe(val => if (val === 3) { this.loading = false; }

I've thought of creating of() wrapper and using concat() around them but I don't think that it's right.


Solution

  • If order is not a concern, you can use forkJoin from rxjs, which works similar to Promise.all,

     forkJoin([...requests])
       .subscribe(_ => this.loading = false;)