Ngrx Component Store: Can I call another effect inside a effect?

Viewed 1930

I'm currently implementing a feature that "open a snackbar"(effect),if close snackbar with action then "open a dialog"(effect) and finally make an API call(effect) after the dialog close.

I want to implement this feature in Component Store,

openDialog = this.effect((trigger$) => 
    trigger$.pipe( 
    exhuastMap(() => this.dialog.open(comp).afterClosed().pipe(
    tap((result) => this.callApi(result))))))

snackBar = this.effect((trigger$)=>
   trigger$.pipe(
   exhuastMap(()=> this.snackBar.open("test","OK").onAction().pipe(
   tap(() => this.openDialog())))))

I noticed that the source implementation of effect() will return a subscription, so is calling another effect inside an effect OK or not? If not, I will need to create additional states to trigger above effects or convert some of them into normal function in the service.

2 Answers

Looking at the source code on GitHub, there should be no problem with calling one effect from another. The effect function doesn't do that much. It will just push the values you call the effect with to a Subject (your trigger$), so it shouldn't matter where you call it from.

You can create a callback function and passing to openDialog effect from snackBar effect , like this:

readonly openDialog = this.effect<{
        whenApiDone: () => void
    }>((arg$) => {
       return arg$.pipe(
           tap((arg) => {
               const isDone = ...;
               if(isDone){
                   arg.whenApiDone();
               }
           })
       )
    };
            


    readonly snackBar = this.effect<{
        whenApiDone: () => void
    }>((arg$) => {
        return arg$.pipe(
                // doSomeThing...
                tap(() => this.openDialog(arg))
            )
    }
Related