在rxjs中基于布尔可观察性的条件可观察性转换

时间:2018-07-29 11:52:10

标签: angular rxjs rxjs6

如何基于布尔可观察值来编辑我的可观察值,只要此布尔可观察值将被更改,$ships可观察值将被转换。

areShipsExpanded$: Observable<boolean>;
ships$: Observable<Ship>;

this.ships$ = this.shipsDataSource.getData().pipe(
    map(s => {
          if(this.areShipsExpanded$) {
              // do something with s
          } else {
              // do something else with s
          }
    return s;
})

当然会使用ships$ | async

上面的代码不正确,因为当this.areShipsExpanded$更改时,Observable不会再次转换。

1 个答案:

答案 0 :(得分:2)

areShipsExpanded$: Observable<boolean>;
ships$: Observable<Ship>;

this.ships$ = this.shipsDataSource.getData().pipe(
combineLatest(this.areShipsExpanded$),
map(([ships, expanded]) => {
      if(expanded) {
          // do something with ships
      } else {
          // do something else with ships
      }
return ships;
})