SharedFlow
, by default, drop elements and the buffer if there's no subscriber. This is the intended behavior of SharedFlow
.
Sometimes you need a SharedFlow
that hold onto elements until some subscriber comes along and start collecting elements.
This SharedFlow
implementation does just that.
// create the ChannelSharedFlow
val shared = ChannelSharedFlow<String>(
scope = scope, // use the scope that makes sense for you
)
shared.emit("Hi") // suspend function
This SharedFlow will not consume until there's at least 1 subscriber to receive events. This means you'll not miss any events even if you have no subscriber for a while. And if there are multiple at the same time they'll all receive.
It uses a Channel
under the hood to keep the buffer and build a SharedFlow
on top of it using the given scope.
When the scope is canceled the channel
is also closed.
This snipped of code demonstrate it: https://pl.kotl.in/69JeANrYg
To install just copy ChannelSharedFlow.kt
in your codebase, you can apply your own package but keep the License comment.
You are free to edit the code as per the Apache License 2.0 if you are in doubt on what you can do check this.