package com.narutohuo.xindazhou.common.ui

import androidx.fragment.app.Fragment
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> Fragment.observeStateFlow(
    stateFlow: StateFlow<T>,
    action: (T) -> Unit
) {
    lifecycleScope.launch {
        stateFlow.collect { action(it) }
    }
}

