Rxjs concat Observable 有条件

Rxjs concat Observable with condition

我正在尝试根据条件执行休息呼叫。该调用将被执行,但根据条件,它将在另一个 rest 调用之后执行。 目前,我尝试过这种方式,但我确定这不是最好的方式:

    if(!checkTokenValidation()) {
       this.service.getToken().pipe(
          map(response => {
             setToken(response);
          })
       ).subscribe(() => {
          this.service.search().subscribe(data => {
             ...
          })
       })
    } else {
       this.service.search().subscribe(data => {
             ...
          })  
    }

我需要在每种情况下进行搜索,但如果令牌无效,我需要先获取新令牌。 有没有办法在没有冗余代码的情况下做到这一点? 谢谢

一种方法如下:

    import { EMPTY, of } from "rxjs";
    import { map, tap, switchMap } from "rxjs/operators";
    
    // if token is valid, create an empty observable, else set the observable to the service.getToken api call
    var obs$ = checkTokenValidation() ? of(EMPTY) : this.service.getToken().pipe(map(response => setToken(response));
    // take the first observable and then map it to a new observable, a.k.a. the response from the service.search api call
    obs$.pipe(switchMap(() => this.service.search())
        .subscribe(data => {
             ...
      });

看起来您正在做的事情依赖于您没有明确管理的某些状态。这很好,但在像 RxJS 这样的声明式库中,它总是会显得有些尴尬。您需要令牌,但我立即 ignoreElements.

你可能觉得这很奇怪,但像这样的东西应该有用:

( checkTokenValidation() ?
  EMPTY :
  this.service.getToken()
).pipe(
  tap(response => setToken(response)),
  ignoreElements(),
  concatWith(this.service.search())
).subscribe(data => {
  // ...
});