RxJs chaining observables with subscriptions

185 Views Asked by At

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.

2

There are 2 best solutions below

0
ABOS On BEST ANSWER

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

 forkJoin([...requests])
   .subscribe(_ => this.loading = false;) 
0
Ankur Shah On

Please use the forkjoin from RxJs

Plunker Demo link

 ngOnInit() {
    forkJoin(
      this._myService.makeRequest('Request One', 2000),
      this._myService.makeRequest('Request Two', 1000) 
      this._myService.makeRequest('Request Three', 3000) 
    )
    .subscribe(([res1, res2, res3]) => {
      this.propOne = res1;
      this.propTwo = res2;
      this.propThree = res3;
    });
  }

Ref from :