1. What is sharedFlow
SharedFlow
It's in the Kotlin coroutineFlow
A kind ofHot Flow, used to be between multiple subscribersShared events or data streams. It's suitable for handlingOne-time event(such as navigation, pop-up windows, Toast, refresh notifications, etc.), rather than persistent state.
✅ What is SharedFlow?
SharedFlow
yesFlow
An extension of the company has the following characteristics:
characteristic | describe |
---|---|
Hot flow | Once triggered, it will be sent even if no one listens. |
Multiple subscribers | All active subscribers receive events |
Not retaining the latest value (unless replay is set) | Not likeStateFlow That way there is always a current value |
Configurable buffer and replay | Controls whether events are cached, discarded, or queued |
It's essentially aEvent broadcaster”。
✅ Common usage scenarios
📍 1. One-time UI event
- Toast pop-up window
- SnackBar Tips
- Navigation Jump
- Close the page
- Dialog display/cancel
These events are "one-time" and do not need to be saved and should not be triggered repeatedly, so they are suitable forSharedFlow
。
sealed class UiEvent { data class ShowToast(val message: String) : UiEvent() object NavigateToHome : UiEvent() }
// ViewModelprivate val _uiEvent = MutableSharedFlow<UiEvent>() val uiEvent = _uiEvent.asSharedFlow() fun loginSuccess() { { _uiEvent.emit() } }
// Fragment { { event -> when (event) { is -> showToast() is -> navigate() } } }
📍 2. Streaming notification
- Notify other modules to refresh data
- Updated page for data pull completion notification
- ViewModel sends a signal to the UI
📍 3. Replace LiveData<Event> to solve the problem of repeated consumption
Traditional useLiveData<Event<T>>
orSingleLiveEvent
Handle one-time events, the code is complex and inelegant, andSharedFlow
It is an officially recommended alternative.
✅ Typical usage of SharedFlow in company projects
layer | How to use |
---|---|
ViewModel | useMutableSharedFlow Send events |
UI(Activity/Fragment) | usecollect Listen to events and make UI responses |
Tool class/middle layer | It can also be used to broadcast notifications and distribute events |
Example: Jump + pop up after login
// ViewModel val eventFlow = MutableSharedFlow<UiEvent>() suspend fun login(username: String, pwd: String) { if (doLogin(username, pwd)) { (("Login successfully")) () } }
✅ Comparison with other Flow types
type | Is it hot? | Is it variable | Whether to retain value | Scene |
---|---|---|---|---|
Flow | ❌ Cold flow | ❌ | ❌ | One-time data flow |
SharedFlow | ✅ Hot flow | ✅ | ❌ (replay can be set) | One-time event broadcast |
StateFlow | ✅ Hot flow | ✅ | ✅ (The initial value must be) | Status management (UI status, progress, etc.) |
✅ In a summary sentence:
SharedFlow
= KotlinHandle one-time eventsRecommended tools, suitable forViewModel → UI layer passes toast, navigation, pop-ups and other short-term behaviors,CompareLiveData
More modern and controllable.
2. How to deal with backpressure in sharedFlow?
✅ 1. How does SharedFlow handle backpressure?
SharedFlow
yesHot stream, meaning that the data will be sent immediately, not likeFlow
Wait for subscribers to collect that way. This means:
- If the launch is too fast (such as multiple consecutive emits)
- And subscribers haven't had time to collect
- Data may be discarded or cached to wait
This requires aCache Policy"To decide how to process these "unable time to process" data - This is what SharedFlowbufferandOverflow policy (onBufferOverflow)。
✅ 2. The meaning of replay = 2, extraBufferCapacity = 5
val sharedFlow = MutableSharedFlow<Int>( replay = 2, extraBufferCapacity = 5 )
These two control two cache areas:
parameter | meaning |
---|---|
replay = 2 |
Each new subscriber willReceive the first 2 values immediately(i.e. "playback value") |
extraBufferCapacity = 5 |
In addition to the replay buffer, temporary cache is also allowed.Up to 5 data |
💡 Total buffer size =replay + extraBufferCapacity
That is, the above configuration can be buffered in totalUp to 7 data。
This means that without collect, up to 7 pieces of data can be emitted without failure or loss.
✅ 3. onBufferOverflow = DROP_OLDEST / DROP_LATEST / SUSPEND What is?
This is controlThe buffer is fullWhen continuing the strategy of emit, what will be done with the strategy.
Supported policies:
Strategy name | explain |
---|---|
DROP_OLDEST |
Throw away the earliest emit data (first in first out) |
DROP_LATEST |
Lost the newly transmitted data (called emit) |
SUSPEND (default) |
suspend emit call, until the buffer has space (safe but may block) |
Example description:
val flow = MutableSharedFlow<Int>( replay = 1, extraBufferCapacity = 2, onBufferOverflow = BufferOverflow.DROP_OLDEST )
At this time, the total buffers are 3:
- If you continuously emit the 1, 2, 3rd item → you can enter the buffer.
- If no one is collect → buffer is full when emit Article 4.
-
DROP_OLDEST
Strategy: WillArticle 1 Value Removal, retain 2, 3, 4.
🔄 emit() and tryEmit():
-
emit()
yesSuspend function, maysuspend
(If the buffer is full and the policy isSUSPEND
)。 -
tryEmit()
yesNon-hanging,returntrue/false
Indicates whether the launch is successful.
✅ In a summary sentence:
Configuration Items | significance |
---|---|
replay |
How many "historical values" can new subscribers receive |
extraBufferCapacity |
How many new values can be temporarily saved without collecting |
onBufferOverflow |
When the cache is full, whether to throw out old, new, or wait |
Total cache |
replay + extraBufferCapacity Piece of data |
This is the end of this article about the complete tutorial of flow sharedFlow in kotlin. For more related content of kotlin sharedFlow, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!