Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In RxJS, why does a pipe get executed once for each subscription?

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)

like image 782
Marko Kacanski Avatar asked Oct 18 '18 13:10

Marko Kacanski


People also ask

Does pipe subscribe in RxJS?

pipe() takes a bunch of RxJS operators as arguments such as filter and map separated by comma and run them in the sequence they are added and finally returns an RxJS Observable . To get the result we need to subscribe() to the returned Observable.

Is pipe same as subscribe?

The pipe method is for chaining observable operators, and the subscribe is for activating the observable and listening for emitted values. The pipe method was added to allow webpack to drop unused operators from the final JavaScript bundle. It makes it easier to build smaller files.

Does pipe subscribe to Observable?

A Pipeable Operator is essentially a pure function which takes one Observable as input and generates another Observable as output. Subscribing to the output Observable will also subscribe to the input Observable.

Why we use pipe with subscribe in angular?

The pipe method of the Angular Observable is used to chain multiple operators together. We can use the pipe as a standalone method, which helps us to reuse it at multiple places or as an instance method.


1 Answers

Because Observable sequences are cold by default, each subscription will have a separate set of site effects.

If you want your side effect to be executed only once - you can share subscription by broadcasting a single subscription to multiple subscribers. To do this you can use share, shareReplay, etc.

To better understand how it works, what is "cold" and publish, refer to the RxJS v4 documentation:

4.8 Use the publish operator to share side-effects

like image 84
Oles Savluk Avatar answered Sep 26 '22 14:09

Oles Savluk