user2836797
user2836797

Reputation:

Why is it important to call publish() before replay()

I've read many rx examples about publish() and replay(). In all tutorials, they say it's important to call publish() before calling replay(). Why is this so? What happens if you call replay() and never call publish()? It seems like the replay() operator would subscribe to the source observable and begin caching. Then anybody who comes along would get the same, complete data stream. The only reason I can see publish() changing the game is that it would delay subscription to the source observable until connect() is called. Is this right?

Upvotes: 4

Views: 2541

Answers (1)

akarnokd
akarnokd

Reputation: 69997

You usually apply one or the other, but not both at the same time because publish().replay() has no practical difference to a plain replay() and replay().publish() is just a recipe for late consumers to not see the whole sequence.

In all tutorials, they say it's important to call publish() before calling replay().

This is definitely wrong, where did you read it exactly?

Is this right?

Both operators return a ConnectableObservable and you have to call connect in both cases to start the sequences. In both cases you should prepare consumers before calling connect or use autoConnect(n) to start the sequence after n consumers.

The difference between publish and replay that the latter caches some or all items and replays them to consumers no matter when they subscribe. The former doesn't retain any items, not even the latest like BehaviorSubject, and dispatches the item to consumers who are subscribed to it at that exact time.

Upvotes: 8

Related Questions