Can I get rxjs observables to output unique/cloned objects to each subscriber?

Viewed 3226

I want to make sure that object references that are passed through an observable aren't shared between subscribers, so that different subscribers aren't affected by each other manipulating the same object.

Right now I am just cloning the received object in each subscribe call, but this is error prone as I need to make sure to do this in every subscribe. I'd really like to be able enforce this for all subscribers to an observable. Maybe with an operator?

Doing a clone in a .map on the observable only breaks the reference between the source and the subscribers, which only gets me partially to where I want to be.

1 Answers

A .map() is enough, unless there's a .share() after it:

var rxjs = require("rxjs")

var o = new rxjs.BehaviorSubject({id: 1})
                .map(it => ({...it}))
o.subscribe(it => {
    it.a = 1;
    console.log(it)
})
o.subscribe(it => {
    it.b = 2;
    console.log(it)
})

Run: https://runkit.com/embed/xwuk9xlo6yhf

Doing a clone in a .map on the observable only breaks the reference between the source and the subscribers, which only gets me partially to where I want to be.

I'm confused. What's missing?

Related