如何从观察者中返回?

时间:2017-04-14 12:27:25

标签: rxjs rxjs5 ngrx

我试图返回过滤器功能,但返回似乎不适用于回调。这里this.store.let(getIsPersonalized$)是一个可观察的发射布尔值,this.store.let(getPlayerSearchResults$)是一个可观察的发射视频类对象。 如何同步运行,我可以完全避免异步回调,因为我无法修改从商店收到的observable。

isPersonalized$ = this.store.let(getIsPersonalized$);
videos$ = this.store.let(getPlayerSearchResults$)                       
                    .map((vids) => this.myFilter(vids));

myFilter(vids) {
   this.isPersonalized$.subscribe((x){
      if(x){
         return this.fileterX(vids);//Return from here
      }
      else {
         return this.filterY(vids);//Or Return from here
      }
  });
}

fileterX(vids) {
  return vids.filter((vid) => vids.views>100;);
}

fileterY(vids) {
  return vids.filter((vid) => vids.views<20;);
}

2 个答案:

答案 0 :(得分:0)

我以这种方式工作,如果你能在isPersonalized$的订阅上获得分支,你根本不需要myFilter(vids)。这是更新的代码。

  this.store.let(getIsPersonalized$);
  videos$: Observable<any>;

  ngOnInit() {
    this.isPersonalized$.subscribe((x) => {
      if (x) {
        this.videos$ = this.store.let(getPlayerSearchResults$)
                        .map((vids) => this. fileterX(vids));
      } else {
        this.videos$ = this.store.let(getPlayerSearchResults$)
                        .map((vids) => this. fileterY(vids));
      }
    });
  }

  fileterX(vids) {
    return vids.filter((vid) => vids.views>100;);
  }

  fileterY(vids) {
    return vids.filter((vid) => vids.views<20;);
  }

答案 1 :(得分:0)

看起来你想在地图函数中评估isPersonalized$的最新值,我会通过withLatestFrom进行评估(示例:第一个每5秒切换一次true/false,第二个每1秒发出越来越多的数字:

const isPersonalized$ = Rx.Observable.interval(5000)
  .map(value => value % 2 === 0);
const getPlayerSearchResults$ = Rx.Observable.interval(1000)
  .withLatestFrom(isPersonalized$)
  .map(bothValues => {
    const searchResult = bothValues[0];
    const isPersonalized = bothValues[1];
    ...
  });