android compose mvi
android compose mvi
·
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) }) }
更多推荐
已为社区贡献3条内容
所有评论(0)