| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- package com.narutohuo.xindazhou.common.ui
- import androidx.appcompat.app.AppCompatActivity
- import androidx.lifecycle.lifecycleScope
- import kotlinx.coroutines.flow.StateFlow
- import kotlinx.coroutines.launch
- /**
- * 观察 StateFlow 的便捷扩展函数
- *
- * 简化业务层代码,避免每次都写 lifecycleScope.launch { flow.collect { } }
- *
- * 使用方式:
- * ```kotlin
- * override fun initObserver() {
- * observeStateFlow(viewModel.loginState) { state ->
- * when (state) {
- * is LoginState.Loading -> showLoading()
- * is LoginState.Success -> {
- * hideLoading()
- * showSuccess(state.message)
- * }
- * is LoginState.Error -> {
- * hideLoading()
- * showError(state.message)
- * }
- * }
- * }
- * }
- * ```
- */
- fun <T> AppCompatActivity.observeStateFlow(
- stateFlow: StateFlow<T>,
- action: (T) -> Unit
- ) {
- lifecycleScope.launch {
- stateFlow.collect { action(it) }
- }
- }
|