StateFlow
andSharedFlow
Yes KotlinCoroutinesTwo types ofReactive Streams, used to handle asynchronous data flows in applications, similar to RxJavaObservable
orFlowable
, but lighter and deeply integrated with Kotlin coroutines.
1. StateFlow (state flow)
StateFlow
It's a kindHot Flow, it stores the current state value and notifies all subscribers when the state changes.
Features
- Must have an initial value(can't be empty).
- Only the latest value is retained(New subscribers will receive the current value immediately).
- yes
SharedFlow
Special circumstances (equivalent toreplay=1
ofSharedFlow
)。 -
Applicable to UI status management(like
ViewModel
Expose UI status).
Example
// Define StateFlow (usually in ViewModel)private val _counterState = MutableStateFlow(0) // Initial value 0val counterState: StateFlow<Int> = _counterState.asStateFlow() // Update the valuefun increment() { _counterState.value++ // Automatically notify all subscribers} // Listen in Activity/Fragment { { value -> = "Count: $value" } }
2. SharedFlow (Shared Stream)
SharedFlow
It's also aHot flow, but it does not store the state, but is used forBroadcast Events(such as one-time events, notifications, etc.).
Features
- No initial value(Any amount of data can be sent).
-
The cache size can be configured(
replay
Controls how much historical data a new subscriber can receive). - Suitable for event bus, notification and other scenarios(such as Toast messages, navigation events).
Example
// Define SharedFlow (usually in ViewModel)private val _toastEvent = MutableSharedFlow<String>() // No initial valueval toastEvent: SharedFlow<String> = _toastEvent.asSharedFlow() // Send eventsfun showToast(message: String) { { _toastEvent.emit(message) // Send events } } // Listen in Activity/Fragment { { message -> (this, message, Toast.LENGTH_SHORT).show() } }
StateFlow
vs SharedFlow
characteristic | StateFlow |
SharedFlow |
---|---|---|
Initial value | ✅ Must have | ❌ No need |
Cache historical data | Only the latest value | Configurable (replay ) |
Applicable scenarios | UI status management (such asLiveData Replacement) |
Event bus, notification |
Is it hot? | ✅ Yes | ✅ Yes |
Thread safety | ✅ Yes (within coroutine scope) | ✅ Yes |
Therefore, the following code is an example:
/** * Application center data changes, update the display of the application center widget */ private fun () = { { list -> (TAG, "observerAppList setDataList") (list) appItemBinding?.groupNoData?.isVisible = () }.launchIn(coroutineScope) }
Function summary:
The main function of this code is to listen for changes in the application widget list (appWidgets) whenever the list is updated:
Set the new list to the gridAdapterApp to update the UI
Show or hide "no data" prompts based on whether the list is empty or not
All of these operations are executed asynchronously in the coroutine
This is a typical responsive programming mode that automatically updates the UI by observing the data flow, avoiding the need to manually refresh the data.
First is the function definition:
private fun () = {
- This is an extension function of WidgetSelectorViewModel
- Functions are private (private)
- Returns a coroutine starter (launch)
- The function is named observerAppList(), indicating that it is used to observe the application list
Next is the function body:
{ list -> (list) appItemBinding?.groupNoData?.isVisible = () }.launchIn(coroutineScope)
-
appWidgets
Probably oneStateFlow
orSharedFlow
(depending on its definition). -
onEach
The UI will be updated every time the data changes. -
launchIn(coroutineScope)
Indicates that the stream is started within the specified coroutine scope.
Summarize
-
StateFlow
→ For UI state management (e.g.LiveData
alternative). -
SharedFlow
→ Used for event notifications (such as Toast, navigation events). - Both are hot streams, and data will be sent even if there is no subscriber.
- Usually combined
ViewModel
+collect
Use to implement responsive UI updates.
If yoursappWidgets
It is the status of an application list, so it is more suitable for useStateFlow
; If it is a temporary event (such as refresh completion notification), it is more suitableSharedFlow
。
This is the end of this article about the difference between StateFlow or SharedFlow in Kotlin. For more information about the difference between StateFlow or SharedFlow, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!