1

I've been troubleshooting a pretty nasty bug where I've eventually realized that it was caused by mutation of a nested object that was passed down the stream of observables and it really surprised me since I was thinking that Observables and their payload are immutable. to understand it better I've reproduced the scenario in the following CodeSandBox (check out the console logs).

is it an expected behavior when working with rxjs observables?

gil
  • 2,388
  • 1
  • 21
  • 29
  • You may find the discussion around [this question](https://stackoverflow.com/questions/69946757/behaviorsubject-mutating-current-value-between-subscriptions/69951294?noredirect=1#comment123725133_69951294) helpful. – BizzyBob Apr 11 '22 at 14:44

1 Answers1

0

In your code both streams are referencing the same object from of(obj), that's why you observed the unexpected mutation.

To make data immutable, objDownStream1$ needs to return a copy of the obj instead.

const objDownStream1$ = intervalObj$.pipe(
  map((obj) => {
    return {...obj, nestedObj: { nestedProp: "downStream1Nested" } }
  })
);
Fan Cheung
  • 10,745
  • 3
  • 17
  • 39
  • yeah i've understood the cause , i'm just surprised by the fact that it's possible to pass mutable object over the observable payload. i've expected it to be immutable too with some mechanism under the hood which handles it. when working with a lot of streams thing can go really wrong this way and it super hard to debug – gil Apr 12 '22 at 05:37
  • That happens with other programming languages too unless the language has built-in immutability or we in most cases have to handle them manually. – Fan Cheung Apr 12 '22 at 07:04