Sobes.tech
Middle

What is StateFlow used for in Android development?

sobes.tech AI

Answer from AI

StateFlow is used to represent a data stream that always has a value. It is a "hot" stream and emits the latest value upon subscription.

Main uses:

  • UI state representation: StateFlow is ideal for storing ViewModel state and passing it to an Activity or Fragment.
  • Sharing data: Multiple subscribers can listen to the same StateFlow and receive the current value.
  • Replacing LiveData: In Kotlin projects, StateFlow is often used instead of LiveData due to better integration with coroutines and Kotlin Flow.
// Example of using StateFlow in ViewModel
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class MyViewModel : ViewModel() {

    private val _uiState = MutableStateFlow(MyUiState(isLoading = true, data = null))
    val uiState: StateFlow<MyUiState> = _uiState // Expose as immutable StateFlow

    data class MyUiState(
        val isLoading: Boolean,
        val data: List<String>?
    )

    fun loadData() {
        // Simulate data loading
        _uiState.value = MyUiState(isLoading = false, data = listOf("Item 1", "Item 2"))
    }
}
What is StateFlow used for in Android development… - sobes.tech