Search code examples
angularreduxrxjsngrx

How to wait for data from various observables to perform an action


I have a problem in angular. I want to get data from various observables and take action after all data arrives.

I already tried separately the methods to get address and data Person and if they work well, I leave the example for the case of getting address.

getDireccion() {
    this.store
        .select('direccion')
        .subscribe(({ direccion }) => (this.direccion = direccion))
        .unsubscribe();
}

But now I want to make sure that all the address data and Person data are already there to be able to carry out another action, that's why I'm using forkJoin, but it doesn't work well for me, it doesn't execute the console.log ('responses ==>', response);

forkJoin([ 
    this.store.select('direccion'),
    this.store.select('datosPersona')
]).subscribe((response) => {
    console.log('respuestas ==> ', response);
});

I am using ngrx for state handling


Solution

  • You should use combineLatest, if you want to do something if it changes during the component life cycle, or only select it once by using take(1). The reason it's not working, is because forkJoin waits for the observable to complete and a store select never really completes:

    combineLatest([ 
        this.store.select('direccion'),
        this.store.select('datosPersona')
    ]).subscribe((response) => {
        console.log('respuestas ==> ', response);
    });
    

    forkJoin([ 
        this.store.select('direccion').pipe(take(1)),
        this.store.select('datosPersona').pipe(take(1))
    ]).subscribe((response) => {
        console.log('respuestas ==> ', response);
    });