RXJS ShareReplay Explained With Examples

Da Feng
4 min readSep 22, 2022
Photo by Elaine Casap on Unsplash

ShareReplay: share source and replay specified number of emissions on subscription.

After reading that, I still don’t know much about it. Probably the most used case we know about ShareReplay is when doing HTTP calls, we can call API once, and use ShareReplay(1) to give the results to other subscribers immediately when they subscribe so that we avoid the extra HTTP calls and make our app more efficient.

But hodor….I have a question, does ShareReplay ever complete? What will happen if I use ShareReplay with forkJoin operator? Since forkJoin will emit only after all inner observables finish. What is that refCount parameter, and what is the real usecase for it? Let’s figure it out together!

Why use shareReplay

Before we dive into examples, we need to remember what are the main responsibilities of shareReplay. To me it’s two aspects, and they are just in the name: share and replay.

First, it’s used to share the same result to many subscribers. Whoever wants to subsribe, will have his share (the same emitted value from the source observable). The real world use case will be the HTTP call strategy mentioned above.

Second, the replay . This is to make sure the latter subscriber, who is late for the party will also have his piece of share…

--

--

Da Feng

I am a software developer, write blogs about Typescript, Angular, React, vue, Front-end technologies, also share some of my life stories and good memories here.