How to use RxJava share() operator?

Use Case: Let’s assume, you have an Observable stream from a database for your email inbox which populates your Inbox itself, and also have a count on the top which indicates your unread emails.

Problem: You can’t simply do…

srcObservable.subscribe(::populateList)
srcObservable.filter(::isUnread).subscribe(::showUnreadCount)

Because…

Without share()

There is no “First subscriber: String2” in the output.

So this means, you cannot have multiple subscribers for the same Observable.
The first subscriber gets killed as soon as the second subscriber is registered.

But with share()…

With share()

Hence now you can use:

Observable<String> shared = srcObservable.share()
shared.subscribe(::populateList)
shared.filter(::isUnread).subscribe(::showUnreadCount)

Trivia

share() is a shorthand for publish().refcount(), making share() an RxJava Subject.
And refcount() will kill off the Observable as soon as all observers unsubscribe (marble diagram above). So this property is carried over to share() operator too.

Edit: Another possible solution

You could create a new observable everytime, like so:srcObservable() that provides separate streams. Having separate streams could potentially be duplication of an expensive operation, especially in database. So, the benefit of using share() is that it’s guaranteed to have synchronicity in your UI. That is, your unread count and what you see in the list will be synced correctly. Also, it’s guaranteed to be cheap too. Happy coding!


Hi, I’m Rakshak Hegde, an aspiring Google Developers Expert (GDE), on Android and Web especially. I work at Instavans as an Android Dev. Any doubts or just wanna chat, hit me up on Twitter.

Twitter — twitter.com/rakshakhegde

Please hit the clap button if you liked this article.

Also please sign up for my newsletter below. Thank you :)

Like what you read? Give Rakshak R Hegde a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.