1
votes

I'm trying to nest 2 observable and subscribing to both of their results but I cant figure out how to do it.

I want to run the first observable, Use it's result in the second observable and in the subscribe function get both first observable result and the second one..

I've made a very simple example of what I want here

Thanks.

2

2 Answers

3
votes

Updating your snippet, you can simply do something like this:

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

Or, if in the map you intended to use an 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);
})

And using a function:

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

Update, as your request in comment:

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

Update:

    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);
      });
  }
0
votes

There are multiple ways to do this. I would choose 'combineLatest'. CombineLatest takes multiple observables and starts to emit values as soon as all source observables emitted at least one value

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

combine Latest