结合两个平行的可观察量

时间:2017-09-05 15:54:53

标签: javascript rxjs observable rxjs5

我坚持切换观察者。这是一个条件:第一个observable应该总是发出并将作为主值流处理,第二个observable应该产生void值,然后它将作为副作用处理。 我在不同的组合运营商中非常困惑。现在我继续使用concatMap,但它也工作不正确。



window.onload = function() {
  const { Observable } = Rx;
  const one = document.getElementById('one');
  const two = document.getElementById('two');
  const one$ = Observable
        .fromEvent(one, 'click')
        .map(() => [1,2,3,4]);
  const two$ = Observable
        .fromEvent(two, 'click')
        .map(() => void 0);

  const sideEffect = values => console.log('Doing something with data', values);

  one$
        .concatMap(initialValues => two$
          .do(() => sideEffect(initialValues))
          .map(() => initialValues))
        .subscribe(x => alert(JSON.stringify(x, null, 2)))
}

<script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/Rx.js"></script>
<button id="one">One</button>
<button id="two">Two</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

如果$two需要修改$one中的最后一个值,然后发出该修改后的值,则可以创建行为主题。

  const values$ = new BehaviorSubject();
  const one$ = Observable
        .fromEvent(one, 'click')
        .map(() => [1,2,3,4]);
  const two$ = Observable
        .fromEvent(two, 'click')
        .map(() => void 0);

  const sideEffect = values => console.log('Doing something with data', values);

  one$.subscribe(values => {
    values$.next(values);
  });
  two$.subscribe(() => {
    let currentValue = values$.value;
    let modifiedValue = sideEffect(currentValue);
    values$.next(modifiedValue);
  });

  values$.subscribe(x => alert(JSON.stringify(x, null, 2)))