'Rxjs observable emit in order

how can i subscribe for example three observables, and to emit when one of them emit new value depend on the order they are, like forkJoin but emit but the order of them is important so if ob3 emit first, i want the value of obv1 to be null, also obv2 and only obv3 that was emitted will have value

for example

forkJoin(obs1,obs2,ob3)
.subscribe([ob1v,ob2v,ob3v]=>{

 if (obv1v){ 'do somthing'}
 if (obv2v){ 'do somthing'}
 if (obv3v){ 'do somthing'}
})

thanks



Solution 1:[1]

Maybe combineLatest with an initial value would work for you. combineLatest will emit the latest value from each source observable whenever any of its sources emit. However, it doesn't emit for the first time until all sources have emitted at least one value.

We can use startWith to overcome this by providing an initial value for each source.

combineLatest([
  obs1.pipe(startWith(null)),
  obs2.pipe(startWith(null)),
  obs3.pipe(startWith(null)),
])
  .pipe(
    skip(1) // prevent emitting initial [null, null, null] value
  )
  .subscribe(([v1, v2, v3]) => {
    // do something here
  });

You can see the output in this StackBlitz.

Solution 2:[2]

It seems that you want to do different thing for every observable. Maybe you shouldn't gorup them? If you want to group them and do different side effect for every one of them you can do something similar to BizzyBob anwer but instead of having if statements in subscribe use tap() operator for every stream. Something like this:


combineLatest([
  obs1.pipe(tap(() =>  'do somthing'),
  obs2.pipe(tap(() =>  'do somthing')),
  obs3.pipe(tap(() =>  'do somthing')),
])
  .subscribe(([v1, v2, v3]) => {
  });

Good practise is not to use subscribe method but instead set this stream to some property in component and than use async pipe in the template.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BizzyBob
Solution 2 brunoj