0

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.

Sergey
  • 7,184
  • 13
  • 42
  • 85
  • concat should work if order is a concern, why do you think that's not right? – ABOS Feb 20 '19 at 14:12
  • @ABOS first of all it chains all methods and makes them in order, meanwhile I could benefit from simultaneous requests. Moreover it's an observable of observable result which doesn't seem right. – Sergey Feb 20 '19 at 14:13
  • if order is not a concern, you can use forkJoin. – ABOS Feb 20 '19 at 14:14
  • Thanks. That worked for me. You may post it as an answer I will mark it. – Sergey Feb 20 '19 at 14:22

2 Answers2

1

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

 forkJoin([...requests])
   .subscribe(_ => this.loading = false;) 
ABOS
  • 3,723
  • 3
  • 17
  • 23
-1

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 :

Ankur Shah
  • 412
  • 6
  • 16