Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an observable depend on another observable

I have a problem understanding the order of events when building 2 observables that depend on the same underlying source. I hope you can not only help me with a working solution, but also explain why I get the outcome below. My goal is that observable2 never emits before observable1.

Code

const filters$ = new Subject();

const observable1 = filters$.pipe(
  map(() => 'obersvable1')
);

const observable2 = observable1.pipe(
  map(() => 'observable2')
)

observable2.subscribe((v) => console.log(v));
observable1.subscribe((v) => console.log(v));

Expected outcome

observable1
observable2

Actual outcome

observable2
observable1

The problem is that when the filters$ subject emits, observable2 emits first? 🤷🏻‍♂️

I have tried using the mergeMap operator on observable2, to make it "depend" on observable1 --> but to no help at all.

Reproduce

Here is a link to a stackblitz with typescript and rxjs.

like image 641
DauleDK Avatar asked Sep 25 '19 10:09

DauleDK


1 Answers

You can make the emissions from observable1 asynchronous before passing them to observable2:

const observable2 = observable1.pipe(
  observeOn(asyncScheduler),
  map(() => 'observable2')
);

Your updated demo: https://stackblitz.com/edit/rxjs-xqcyqk?file=index.ts

like image 188
martin Avatar answered Sep 29 '22 02:09

martin