Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use `publishReplay` vs `shareReplay`?

I already know that

  • publish shares a single subscription and also returns a ConnectableObservable ( so we have to Connect())

  • Share() is publish().refcount()

The Replay postfix is pretty obvious, it returns its last emission/s.

Let's take for example an Angular HTTP request with present AND future subscription :

<p>{{ (person | async)?.id   }}</p> //present markup  <p *ngIf=”show”>{{ (person | async)?.userId }}</p> <!-- future markup --> 

If I don't want multiple http requests I can use :

publishReplay().Connect() 

But I can also use: shareReplay(), but I'm sure that there is one here that is more correct to use than the other.

Question :

When should I use publishReplay vs shareReplay? What will be the difference in terms of that HTTP present & future request?

NB Why there's no documentation about shareReplay?

like image 300
Royi Namir Avatar asked Dec 21 '17 13:12

Royi Namir


People also ask

When use shareReplay?

You generally want to use shareReplay when you have side-effects or taxing computations that you do not wish to be executed amongst multiple subscribers. It may also be valuable in situations where you know you will have late subscribers to a stream that need access to previously emitted values.

What is publishReplay?

publishReplay makes it possible to share a single subscription to the underlying stream between multiple subscribers and replay a set of values that happened before the underlying stream completed.

Does shareReplay unsubscribe?

With the fix, shareReplay will effect the behaviour you are looking for, as it will now unsubscribe from the source only when the source completes or errors. When the number of subscribers to the shared observable drops to zero, the shared observable will remain subscribed to the source.


Video Answer


1 Answers

shareReplay() is basically publishReplay().refCount()

Definitely not.

Both shareReplay and publishReplay (+ calling connect on it) will make the observable behind it hot.

But the very important difference between them is:

  • shareReplay: won't stop emitting until it's completed, no matter if there are no subscriptions anymore or not.
  • publishReplay: will stop after the last subscriber unsubscribes if used together with refCount

Imho this is a crucial information.

like image 81
Flash Avatar answered Oct 06 '22 11:10

Flash