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

前端 未结 3 1326
青春惊慌失措
青春惊慌失措 2020-12-25 12:17

I already know that

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

相关标签:
3条回答
  • 2020-12-25 12:39

    publishReplay allows you to controls when the subscription starts. shareReplay will start automatically upon the first subscription.

    Generally, if the observable is to be used in a template (html file) use shareReplay. The advantage being you won't have to worry about unsubscribing etc.

    0 讨论(0)
  • 2020-12-25 12:49

    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.

    0 讨论(0)
  • 2020-12-25 13:02

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

    Here is a great article explaingin just that in detail: "Angular Async Pipes  - Beware the share"

    Edit:

    The right thing to say is:

    shareReplay() is similar to publishReplay().refCount()

    see @DevRok's answer for more info why they are not exactly the same.

    0 讨论(0)
提交回复
热议问题