取消ngrx效果中的计时器

Sco*_*t w 2 ngrx ngrx-effects angular ngrx-store

我有一个微调器,我希望微调器在显示之前等待x秒.但是,如果在微调器等待超时完成期间调用REQUEST_DEACTIVATE_SPINNER,则应该停止触发ACTIVATE_SPINNER操作.阿卡我想取消活动计时器.这就是我到目前为止所拥有的.

  @Effect() spinnerActive$ = this.actions$
    .ofType(REQUEST_ACTIVATE_SPINNER, REQUEST_DEACTIVATE_SPINNER)
    .switchMap(action => {
      // create a timer and return it active event sent when timer completes
      if (action.type === REQUEST_ACTIVATE_SPINNER) {
        timer$ = Observable.timer(action.payload.delay || 0)
        .switchMap(() =>
          Observable.of({type: ACTIVATE_SPINNER})
        );
      }

      if (action.type === REQUEST_DEACTIVATE_SPINNER) {
        // check to see if a timer is running if it is cancel it
        if (timer$) {
          // cancel the timer
        }
        return Observable.of({type: DEACTIVATE_SPINNER});
      }
    });
Run Code Online (Sandbox Code Playgroud)

有些机构可能会告诉我们如何取消正在返回效果的计时器.

car*_*ant 7

您应该能够使用takeUntil操作员解决您的问题.

你可以使用它来完成观察到在switchMapREQUEST_ACTIVATE_SPINNER一个效果时REQUEST_DEACTIVATE_SPINNER收到的行动.

请注意,现在有两种效果,因为REQUEST_DEACTIVATE_SPINNER效果现在与REQUEST_ACTIVATE_SPINNER效果无关:

@Effect() spinnerActive$ = this.actions$
  .ofType(REQUEST_ACTIVATE_SPINNER)
  .switchMap(action => Observable
    .timer(action.payload.delay || 0)
    .takeUntil(this.actions$.ofType(REQUEST_DEACTIVATE_SPINNER))
    .switchMap(() => Observable.of({ type: ACTIVATE_SPINNER })
  );

@Effect() spinnerDeactive$ = this.actions$
  .ofType(REQUEST_DEACTIVATE_SPINNER)
  .switchMap(action => Observable.of({ type: DEACTIVATE_SPINNER }));
Run Code Online (Sandbox Code Playgroud)

此外,一些switchMap运营商是不必要的,可以替换为mapTo:

@Effect() spinnerActive$ = this.actions$
  .ofType(REQUEST_ACTIVATE_SPINNER)
  .switchMap(action => Observable
    .timer(action.payload.delay || 0)
    .takeUntil(this.actions$.ofType(REQUEST_DEACTIVATE_SPINNER))
    .mapTo({ type: ACTIVATE_SPINNER })
  );

@Effect() spinnerDeactive$ = this.actions$
  .ofType(REQUEST_DEACTIVATE_SPINNER)
  .mapTo({ type: DEACTIVATE_SPINNER });
Run Code Online (Sandbox Code Playgroud)