[RxJS] exhaustMap vs switchMap vs concatMap

exhaustMap: It drop the outter observable, just return the inner observable, and it waits until previous observable complete before emit next observable.this

Good for canceling extra network outter request, for example click (outter) request trigger network (inner) request, if network (inner) request is not finished yet, new click (outter) request will be ignored.spa

Use case: "Save" button, avoid send extra network request to the server.code

 

switchMap: Map to inner observable, cancel previous request.orm

  // exhaustMap

  @Effect()
  login$ = this.actions$
    .ofType(Auth.LOGIN)
    .map((action: Auth.Login) => action.payload)
    .exhaustMap((auth: Authenticate) =>
      this.authService
        .loginUser(auth.email, auth.password))
    .map(user => new Auth.LoginSuccess({user}))
    .catch(error => of(new Auth.LoginFailure(error)));


// switchMap

  @Effect()
  login$ = this.actions$
    .ofType(Auth.LOGIN)
    .map((action: Auth.Login) => action.payload)
    .switchMap((auth: Authenticate) =>
      this.authService
        .loginUser(auth.email, auth.password)
        .map(user => new Auth.LoginSuccess({user}))
        .catch(error => of(new Auth.LoginFailure(error)));
     )
.shareReplay(1)

SwitchMap has cancelling logic.server

 

concatMap:blog

Good for waiting previous network request finished. For example, We have a form, when use is typing, we also want to save the data, send to the server. it

Every network request will send in order, and wait pervious network request finished.io

相關文章
相關標籤/搜索