Understanding Ngrx OnRunEffects

2k Views Asked by At

I have several Effect listeners that need to run until the user has logged out. As such, I'm trying to implement OnRunEffects.

A segment of my user.actions.ts is:

export const LOAD_USER = '[Users] Load User';

export class LoadUser implements Action {
  readonly type = LOAD_USER;
}

export type UserActions = LoadUser;

I'm trying to implement OnRunEffects as:

ngrxOnRunEffects(resolvedEffects: Observable<EffectNotification>) {
    return this.actions
                .ofType(UsersActions.LOAD_USER)
                .exhaustMap(() => resolvedEffects.takeUntil(AuthActions.LOGOUT_SUCCESS)
}

However, takeUntil is complaining that it needs as Observable. So I tried:

ngrxOnRunEffects(resolvedEffects: Observable<EffectNotification>) {
        return this.actions
                    .ofType(UsersActions.LOAD_USER)
                    .exhaustMap(() => resolvedEffects.takeUntil(
                        Observable.of(new AuthActions.LogoutSuccess())
                     )
    }

That in turn, causes the effect to not fire. From reading the code, it looks like it states:

  1. When you see these actions
  2. run the effects
  3. until you see this other action.

What am I doing wrong?

2

There are 2 best solutions below

2
On

Correct me if I'm wrong, but you might not want to run until the user has logged out, you might just want to run those effects if the user is still logged in. If yes, then instead of thinking to takeUntil:

@Effect()
someEffect$: Observable<Action> = this.actions$
  .ofType<Your_Type>(Your_Action)
  .withLatestFrom(this.store$.select(state => state.users.isUserLoggedIn))
  .filter(([action, isUserLoggedIn]) => isUserLoggedIn)
  // here, you'll receive the actions only is the user is logged in
  // ... your code for the effect
3
On

Try this:

ngrxOnRunEffects(resolvedEffects: Observable<EffectNotification>) {
    return this.actions
        .ofType(UsersActions.LOAD_USER)
        .exhaustMap(() => resolvedEffects.takeUntil(this.actions.ofType(AuthActions.LOGOUT_SUCCESS)))
}

Documentation have been updated : https://github.com/ngrx/platform/commit/4b606d581d18866576b9632b0537953c2b6006c4