【问题标题】:switch observable based on previous observable根据之前的 observable 切换 observable
【发布时间】:2021-02-09 15:56:15
【问题描述】:

我有一个 observable A,它返回 boolean observable 并且基于 observable A 的值我需要调用 wither observable B 或 C

observableA = of(true);

observableB(): observable<string> {
}

observableC(): observable<string> {
}

function value () {
   return observableA.pipe(map(value => {
     if(value) {
      return observableB();
     } else {
      return observableC();
    }

}))
}

【问题讨论】:

  • @khizer 的回答会在每次真值发生变化时重新订阅您的基本 observables,可以吗?你的 B 和 C observables 热吗?

标签: observable angular-observable


【解决方案1】:

您可以使用switchMap 运算符代替map

function value () {
   return observableA.pipe(switchMap(value => {
     if(value) {
      return observableB();
     } else {
      return observableC();
    }

}))

【讨论】:

    【解决方案2】:

    为了根据真值区分调用哪个 observable。 示例如下所示

    • case => true => 多项目 10

    • case => false => 多项目 20

    
    import { of, Subject } from "rxjs";
    import { map } from "rxjs/operators";
    
    const observableInvokeOnTruthy$ = of(1, 2, 3, 4, 5);
    const observableInvokeOnFalsy$ = of(1, 2, 3, 4, 5);
    const emitValuesSubject$ = new Subject();
    
    emitValuesSubject$.subscribe(response => {
      if (response) {
        console.log("TRUTHY VALUE:");
        observableInvokeOnTruthy$
          .pipe(
            map(item => {
              return item * 10;
            })
          )
          .subscribe(result => {
            console.log(result);
          });
      } else {
        console.log("FALSY VALUE:");
        observableInvokeOnFalsy$
          .pipe(
            map(item => {
              return item * 20;
            })
          )
          .subscribe(result => {
            console.log(result);
          });
      }
    });
    
    emitValuesSubject$.next(false);
    emitValuesSubject$.next(true);
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 2019-01-07
      • 2017-01-29
      • 1970-01-01
      相关资源
      最近更新 更多