sealed class MainIntent {
    object refresh : MainIntent()
    object loadData : MainIntent()
}
sealed class MainUiState {
    object isLoading : MainUiState()
    object loadError : MainUiState()
    object loadSuccess:MainUiState()
}
class MainViewModel: ViewModel() {

    private val userIntent = MutableSharedFlow<MainIntent>()//接收事件
    private val _state = MutableStateFlow<MainUiState>(MainUiState.isLoading)//用于给activity监听回调使用
    val state: SharedFlow<MainUiState>
        get() = _state

    init {
        viewModelScope.launch {
            userIntent.collect(){//接收广播
                when(it){
                    is MainIntent.refresh -> {
                        _state.value=MainUiState.isLoading
                        println("--data-- 刷新数据")
                    }
                    is MainIntent.loadData -> {
                        _state.value=MainUiState.loadSuccess
                        println("--data-- 请求成功")
                    }
                    else -> {
                        println("--data-- 请求错误")
                        _state.value=MainUiState.loadError
                    }
                }
            }
        }
    }
    fun dispatch(viewAction: MainIntent) {
        try {
            viewModelScope.launch {
                userIntent.emit(viewAction)//发送广播
            }
        } catch (e: Exception) {
        }
    }
}

下面是调用

onCreate方法
var viewModel=MainViewModel()
lifecycleScope.launch {
  viewModel.state.collect{
      when(it){
          is MainUiState.isLoading->{ println("--data-- home isLoading")}
          is MainUiState.loadError->{ println("--data-- home loadError")}
          is MainUiState.loadSuccess->{ println("--data-- home loadSuccess")}
      }
   }
 }
Test(viewModel =viewModel)

@Composable
fun  Test(viewModel: MainViewModel){
    Text(text = "加载数据", modifier = Modifier.clickable {
        viewModel.dispatch(MainIntent.loadData)
    })
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐