2

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

John doe
  • 317
  • 3
  • 5
  • 15
  • What I understood from your OP and comments - You have three observable say `obs1$: Observable` `obs2$: Observable` `obs3$: Observable` - You want to call them inorder,means `obs2$` will be called once `obs1$` is finished and so - You want response as soon as they emits. Did I get it correctly? – Saptarsi Mar 30 '22 at 06:48

2 Answers2

0

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.

BizzyBob
  • 12,309
  • 4
  • 27
  • 51
  • But each time one of them emit, i get the other values as well even if they didn't emit. – John doe Mar 29 '22 at 09:30
  • I do not understand the behavior you want to achieve. Can you please update the question and explain the desired output in all relevant scenarios? (Ex: When obs2 emits first, emission should be...) – BizzyBob Mar 29 '22 at 14:44
0

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.

brunoj
  • 56
  • 3