embarq
embarq

Reputation: 335

Combining two parallel observables

I'm stuck with switching observables. Here's a condition: first observable should always emit and will be handled as main value stream, second observable should produce void value and then it will be handled as a side-effect. I'm very confused in different combining operators. Now I'm staying on concatMap but it also works incorrectly.

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/[email protected]/dist/global/Rx.js"></script>
<button id="one">One</button>
<button id="two">Two</button>

Upvotes: 1

Views: 87

Answers (1)

Pace
Pace

Reputation: 43957

If $two needs to modify the last value from $one and then emit that modified value you could create a behavior subject.

  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)))

Upvotes: 2

Related Questions