rxjs嵌套可观察并组合结果

时间:2017-11-02 15:28:45

标签: rxjs observable

我正试图嵌套2观察并订阅他们的两个结果,但我无法弄清楚如何去做。

我想运行第一个observable,在第二个observable中使用它的结果,在subscribe函数中获取第一个可观察结果和第二个observable结果。

我已经为我想要的here

做了一个非常简单的例子

感谢。

2 个答案:

答案 0 :(得分:2)

更新您的代码段,您可以执行以下操作:

Rx.Observable.of(1)
.map(x=>{
  var y = x * 2;
  return {x, y};
})
.subscribe(res=>{
  console.log(res.x, res.y);
})

或者,如果在地图中您打算使用Observable:

Rx.Observable.of(1)
.switchMap(x=> {
  var y = x * 2;
  return Rx.Observable.of({x, y});
})
.subscribe(res=>{
  console.log(res.x, res.y);
})

使用功能:

function simpleAndDouble$(x) {
  var y = x * 2;
  return Rx.Observable.of({x, y}); 
}

var obs1$ = Rx.Observable.of(1)
.switchMap(x=> simpleAndDouble$(x))
.subscribe(res=>{
  console.log(res.x, res.y);
})

更新,作为评论中的请求:

const subscription = Rx.Observable.of(1)
    .mergeMap(x =>
        Rx.Observable.of(x * 2),
        (x, y) => {
            console.log(x, y);
        })
    .subscribe();

<强>更新

    const one$ = Observable.of(1);
    const two$ = one$.map(x => x * 2);
    const subscription = Observable
      .merge(one$, two$)
      .map(n => [n])
      .reduce((acc, val) => acc.concat(val), [])
      .subscribe((a) => {
        const [x, y] = a;
        console.log('x:', x);
        console.log('y:', y);
      });
  }

答案 1 :(得分:0)

有多种方法可以做到这一点。我会选择'combineLatest'。 CombineLatest采用多个observable并在所有源observable发出至少一个值时开始发出值

let combinedObs = combineLatest([observable1, observable2]);
combinedObs.subscribe((val1, val2) => {
    return val1 * val2
});

combine Latest

相关问题