ActivityExtensions.kt 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package com.narutohuo.xindazhou.common.ui
  2. import androidx.appcompat.app.AppCompatActivity
  3. import androidx.lifecycle.lifecycleScope
  4. import kotlinx.coroutines.flow.StateFlow
  5. import kotlinx.coroutines.launch
  6. /**
  7. * 观察 StateFlow 的便捷扩展函数
  8. *
  9. * 简化业务层代码,避免每次都写 lifecycleScope.launch { flow.collect { } }
  10. *
  11. * 使用方式:
  12. * ```kotlin
  13. * override fun initObserver() {
  14. * observeStateFlow(viewModel.loginState) { state ->
  15. * when (state) {
  16. * is LoginState.Loading -> showLoading()
  17. * is LoginState.Success -> {
  18. * hideLoading()
  19. * showSuccess(state.message)
  20. * }
  21. * is LoginState.Error -> {
  22. * hideLoading()
  23. * showError(state.message)
  24. * }
  25. * }
  26. * }
  27. * }
  28. * ```
  29. */
  30. fun <T> AppCompatActivity.observeStateFlow(
  31. stateFlow: StateFlow<T>,
  32. action: (T) -> Unit
  33. ) {
  34. lifecycleScope.launch {
  35. stateFlow.collect { action(it) }
  36. }
  37. }