Categories
blog kotlin

SharedFlow

Intro

This is a third article in the series, please check out the other two articles here: 1st, 2nd

What is SharedFlow?

SharedFlow is a hot flow, it will emit data even though there are no observers/collectors. It’s important to mention this because everything will make more sense if this basic idea of hot vs cold flows/streams is understood. LiveData was a bit under-engineered in my option due to this fact, it was retrofitted to behave as both hot and cold stream, which did not work well and required some patching after the fact. 

When to use it?

It’s perfect for displaying one-off events like error messages and notifications to users. Since a hot flow will not re-emit values to new subscribers and it does not keep state, it’s impossible to display the same event twice. Although it can be customized, by default, it’s still a hot flow. 

When not to use it?

State management, since it does not keep any state SharedFlow is not suitable for state management, new subscribers won’t get the latest state. This can be tweaked also but by default, it does not work well for state management. 

SharedFlow vs Livedata

Those readers who used SingleLiveData or Event class with LiveData are familiar with hacks required to make LiveData behave like a hot flow. SharedFlow fills in that gap and makes it easy to handle one-off events like error messages. 

Nice to know SharedFlow APIs

With SharedFlow we can control how many last n events are played back to new subscribers, which is handy when we wanna maintain some state. extraBufferCapacity is handy when it comes to slow consumers, extra buffer capacity will let SharedFlow have additional items on top of the replayCache that helps slow subscribers get through all events

Leave a Reply

Your email address will not be published. Required fields are marked *