Search code examples
angularngrxngrx-effects

How to reset ngrx effects on logout ? NGRX Efftects


Tell me please how to reset all effects on some action (user logout)? Id like to reset all effects on LOG_OUT actions. for exaple:

  1. subscribe some effect on some action
  2. trigger takeUntil() inside effect
  3. logout
  4. reset all effects
  5. subscribe same effect on same action again (from step 1) .

at the moment step 5 doesnt work, cause takeUntil() unsubscribe that effect.


Solution

  • I added mergeMap and put takeUntil there. Now its nice.

     @Effect() createConversation$ = this.actions$.pipe(
        ofType(CREATE_CONVERSATION),
        map((action: CreateConversation) => action.payload),
        withLatestFrom(this.store.pipe(select(selectConversation))),
        mergeMap(([message, mdConversation]) => {
          return this.httpService
            .createConversation(mdConversation.data.taskId, message)
            .pipe(
              map(
                result =>
                  new CreateConversationComplete({
                    id: result.data.id,
                    tmpId: mdConversation.data.id
                  })
              ),
              catchError((error: MyError) => {
                if (error.type === MyerrorTypes.NETWORK) {
                  return of(new CreateConversationRetry(message));
                }
                if (error.type === MyerrorTypes.APPLICATION) {
                  return of(new CreateConversationError(mdConversation.data));
                }
              }),
              takeUntil(this.actions$.pipe(ofType(LOG_OUT)))
            );
        })
      );
    
    
    @Effect() createConversationRetry$ = this.actions$.pipe(
            ofType(CREATE_CONVERSATION_RETRY),
            mergeMap((action: CustomAction) =>
              of(action).pipe(
                delay(NETWORK_TIMEOUT),
                map(data => new CreateConversation(action.payload)),
                takeUntil(this.actions$.pipe(ofType(LOG_OUT)))
              )
            )
          );