SoFunction
Updated on 2025-04-13

Analysis of the difference between StateFlow or SharedFlow in Kotlin

StateFlowandSharedFlowYes KotlinCoroutinesTwo types ofReactive Streams, used to handle asynchronous data flows in applications, similar to RxJavaObservableorFlowable, but lighter and deeply integrated with Kotlin coroutines.

1. StateFlow (state flow)

StateFlowIt'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).
  • yesSharedFlowSpecial circumstances (equivalent toreplay=1ofSharedFlow)。
  • Applicable to UI status management(likeViewModelExpose 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)

SharedFlowIt'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 configuredreplayControls 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 asLiveDataReplacement) 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)
  • appWidgetsProbably oneStateFloworSharedFlow(depending on its definition).
  • onEachThe 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.LiveDataalternative).
  • 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 combinedViewModel + collectUse to implement responsive UI updates.

If yoursappWidgetsIt 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!