Observables are a new powerful add-on of Angular 2. Since they can be shared and messages are mutable, never modify a message because the action will affect other consumers.

The domain

I spent part of my last week learning Angular 2 and I was so happy to discover that is using RxJS to expose Observables. Of course the tutorials are a bit too into the hype of Observables, exaggerating their use all around the code for the sake of learning it as fast as possible.

When there is more than one consumer of the stream, you are sharing the Observable; and this is a good way to let different objects to be notified of the new available state.

To share an Observable we must be aware that its execution is gonna be repeated for each subscriber and this is the reason why the framework provides us with the method .share() which simply wraps the first subscribe action and dispatches the message to other subscribers. Have a look the official docs here.

The problem

An Observable is an object which gives access to a stream of messages and can be consumed by different clients, like they exist in other languages and frameworks: the consumer subscribes itself to the stream using the observable API and gets a message each time a new element is injected in the pipeline. Observables can obviously be shared, and this it a key point.

Naturally I expect that if the stream itself is shared, the messages are immutable. Or, in a language like Javascript that doesn’t provide immutability out of the box, they should at least be copied. Instead also the messages are shared.

Let’s see some code:

Just created a list of objects with unique id and then generated an Observable emitting the items. I also chained a side effect using do just to observe (pardon the pun) how sharing works.

Now I create three consumers, simple functions subscribing to the Observable:

The first one prints the original message and then attach a property to it. The second overrides the unique id. The last one just prints the message.

Now I want them to run:

And this is the ouput:

As you can notice the message has been changed while passing across the subscribers that should just read it.

If you want to experiment more with it, I published all the code on my new RxJS playground which is a fork from the great rxjs-babel-es2015-starter by Nader Dabit .

The bottom line

Of course using a message this way doesn’t really make sense, but I found it even in some tutorial like the chat one. Since it is possible, I guess quite a lot of developers will start using this property to generate side effects and cut the corner to meet deadlines instead of thinking more about their architecture.

Don’t do that.

The short time you save doesn’t worth the nights you are going to spend to maintain and debug such a monster. And moreover, this is not reactive at all.