StateFlow 和 SharedFlow 是 Flow API,可让数据流以最佳方式发出状态更新并向多个使用方发出值。与冷数据流不同,它们是热数据流:无论是否有收集器,它们都会保持活跃状态。如需了解热流的工作原理、热流与冷流的区别,以及如何使用 stateIn 和 shareIn 转换冷流,请参阅 Kotlin 文档中的热流。本页介绍了如何在 Android 应用中使用 StateFlow:从 ViewModel 公开界面状态、从界面安全地收集界面状态,以及将 StateFlow 与 LiveData 进行比较。
StateFlow
在 Android 中,StateFlow 非常适合需要让可变状态保持可观察的类。
按照 Kotlin 数据流中的示例,可以从 LatestNewsViewModel 公开 StateFlow,以便 View 能够监听界面状态更新,并自行使屏幕状态在配置更改后继续有效。
class LatestNewsViewModel( private val newsRepository: NewsRepository ) : ViewModel() { // Backing property to avoid state updates from other classes private val _uiState = MutableStateFlow(LatestNewsUiState.Success(emptyList())) // The UI collects from this StateFlow to get its state updates val uiState: StateFlow<LatestNewsUiState> = _uiState init { viewModelScope.launch { newsRepository.favoriteLatestNews // Update UI with the latest favorite news // Writes to the value property of MutableStateFlow, // adding a new element to the flow and updating all // of its collectors .collect { favoriteNews -> _uiState.value = LatestNewsUiState.Success(favoriteNews) } } } } // Represents different states for the LatestNews screen sealed class LatestNewsUiState { data class Success(val news: List<ArticleHeadline>) : LatestNewsUiState() data class Error(val exception: Throwable) : LatestNewsUiState() }
负责更新 MutableStateFlow 的类是生产者,而从 StateFlow 收集的所有类都是消费者。
当新使用方开始从数据流中收集数据时,它将接收信息流中的最近一个状态及任何后续状态。您可在 LiveData 等其他可观察类中找到此操作行为。
在 Jetpack Compose 中,使用 androidx.lifecycle:lifecycle-runtime-compose 工件中的 collectAsStateWithLifecycle 可组合函数收集 StateFlow。此函数会将数据流转换为 Compose State,并在生命周期低于 Lifecycle.State.STARTED 时自动停止收集。如需查看示例,请参阅生命周期感知型数据流收集。
在视图中,像收集任何其他数据流一样,在 repeatOnLifecycle 内收集 StateFlow:
class LatestNewsActivity : ComponentActivity() { private val latestNewsViewModel: LatestNewsViewModel = TODO() // getViewModel() override fun onCreate(savedInstanceState: Bundle?) { // ... // Start a coroutine in the lifecycle scope lifecycleScope.launch { // repeatOnLifecycle launches the block in a new coroutine every time the // lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED. repeatOnLifecycle(Lifecycle.State.STARTED) { // Trigger the flow and start listening for values. // Note that this happens when lifecycle is STARTED and stops // collecting when the lifecycle is STOPPED latestNewsViewModel.uiState.collect { uiState -> // New value received when (uiState) { is LatestNewsUiState.Success -> showFavoriteNews(uiState.news) is LatestNewsUiState.Error -> showError(uiState.exception) } } } } } }
StateFlow、Flow 和 LiveData
StateFlow 和 LiveData 具有相似之处。两者都是可观察的数据容器类,并且在应用架构中使用时,两者都遵循相似模式。
但请注意,StateFlow 和 LiveData 的行为确实有所不同:
StateFlow需要将初始状态传递给构造函数,而LiveData不需要。- 当 View 进入
STOPPED状态时,LiveData.observe()会自动取消注册使用方,而从StateFlow或任何其他数据流收集数据的操作并不会自动停止。如需实现相同的行为,请在 Compose 中使用collectAsStateWithLifecycle收集数据流,或在 View 中从Lifecycle.repeatOnLifecycle代码块收集数据流。
其他数据流资源
- Android 上的 Kotlin 数据流
- 在 Android 上测试 Kotlin 数据流
- 关于 Flow 的 shareIn 和 stateIn 运算符的注意事项
- 从 LiveData 迁移到 Kotlin Flow
- Flows