0

I am using angular4 what I want to achieve is that a function is called after 2 or 3 calls are finished.

example:

  this.Get.firstGet().subscribe( data=> {

               this.test();
          });

  this.Get.secondGet().subscribe( data=> {

               this.test();
          });

  test(){
    //do something when firstGet and secondGet are both finished

   }

thx for the help!

user3356007
  • 393
  • 1
  • 6
  • 20
  • 3
    `forkJoin(this.Get.firstGet(), this.Get.secondGet()).subscribe(([get1, get2]) => this.test())` –  Mar 27 '19 at 09:37

2 Answers2

1

You can use combineLatest from RxJS to wait all inner observables to fire at least once

import { combineLatest } from 'rxjs';
...


combineLatest(
   this.Get.firstGet(),
   this.Get.secondGet()
)
.subscribe(([responseOfFirst, responseOfSecond]) => {
     this.test();
})

Or you can use forkJoin as well: https://www.learnrxjs.io/operators/combination/forkjoin.html

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
1

You are separately calling this.test(); in each subscribe() so by your code you are calling it twice.

I believe what you want is forkJoin, this will only execute the success, error blocks when all the Observables are resolved

forkJoin(this.Get.firstGet(), this.Get.secondGet()).subscribe(([firstGet, secondGet]) => {
    this.test();
})
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51