-
Hi, a sample code that produces my issue is here: https://stackblitz.com/edit/rxjs-mvugpe?file=index.ts I have two observables as sources input1$ and input2$. Now when one of them is updated, some computation is triggered in the observable calculated$.
However, if I move secondSub (line 12) after combined$, or remove it alltogether, the console long in combined$ actually produces the desired input with the CURRENT value of the changed input. This behavior feels very weird to me, could someone explain why it behaves that way and what I could use instead, or confirm that it is an error? Thanks in advance |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
It has to do with the order of subscription.
On the first case, you subscribe to
Then you subscribe to
So now when On the second case everything changes. First you subscribe to
And then you subscribe to Hopefully this made sense, sorry for the long post 😅 . I don't think it's to be considered an error on rxjs, but I think it's a general issue on rxjs that it's sometimes confusing, as you need to understand rxjs' internals (Observables and/or operators) to figure out these kind of things. As for posible solutions, given that If inputs weren't BehaviorSubject, then I think the alternative would be to change combined$ to be: const combined$ = calculated$
.pipe(
observeOn(asyncScheduler),
withLatestFrom(input1$, input2$),
shareReplay(1)
) which basically delays the emissions from |
Beta Was this translation helpful? Give feedback.
It has to do with the order of subscription.
withLatestFrom
is meant to work with any observable, not only BehaviorSubjects and/or shareReplay()-ed observables. So the way it works is that it subscribes to the observables you give it as parameter, and then it will just append the latest value emited from them when a new value comes from source$.On the first case, you subscribe to
calculated$
before you subscribe tocombined$
. What happens here initially iscalculated$
will subscribe toinput1$
andinput2$
, and then you have secondSub subscribed tocalculated$
. The list of subscriptions is as follows:Then you subscri…