I want to have multiple subscriptions to react to an observable event, but I want to log the event as well, so I pipe it through a do()
operator in which I do the logging.
The problem is, the event gets logged once for each of the subscriptions I create!
I'm getting around this at the moment by creating a Subject
and calling next
on it from an event callback, which allows me to log the event once and trigger multiple subscriptions as well.
Here is some code that demonstrates the issue: https://stackblitz.com/edit/rxjs-xerurd
I have a feeling I'm missing something, isn't there a more "RxJS" way of doing this?
EDIT:
I'm not asking for a difference between hot & cold observable, in fact I was using a hot observable - the one created by fromEvent()
and was wondering why does my presumably hot event source behave like it's cold.
I realize now - after reading about share()
- that pipe()
"turns" your observable cold i.e. returns a cold one based on the your source (which may be cold, may be hot)
share()
operator if you want to keep only one subscription to its source. – martinshare()
indeed seems to be what I'm looking for, but could you perhaps (if you know why it is so) explain the reasoning behind such a design? It seems to me that maybe "sharing" should be a default and, "not sharing" should have an operator. – Marko Kacanski