Kotlin ViewModel中StateFlow多次更新失效问题的解决方法
ViewModel中StateFlow状态无法多次更新的问题
问题场景
调用authV1方法时StateFlow状态可正常更新,但调用authV2或reset方法时状态无变化。需明确如何正确复制StateFlow的状态,确保触发更新并让视图展示最新值。视图仅通过列布局展示文本与更新按钮。
相关代码
ViewModel代码
class AuthViewModel: ViewModel() { // transient value/state private val _authEntityMutableStateFlow = MutableStateFlow<AuthEntity>(AuthEntity(token = "")) val authEntityStateFlow = _authEntityMutableStateFlow.asStateFlow() fun update(data: AuthEntity) { // required in kotlin because it does not update by value _authEntityMutableStateFlow.value = _authEntityMutableStateFlow.value.copy(token = data.token) // or authEntityStateFlow? } fun authV1() { viewModelScope.launch { update(AuthRepo.instance.getTestTokenV1()) // this method uses suspend call withContext } } fun authV2() { viewModelScope.launch { AuthRepo.instance.getTestTokenV2() // this method uses return withContext(Dispatchers.IO) { Result.success for testing with fixed value .onSuccess { authRespEntity -> update(authRespEntity.data) } } } fun reset() { update(AuthEntity(token = "")) } }
Composable界面代码
@Composable fun AuthScreen(authViewModel: AuthViewModel = AuthViewModel()) { val authEntityStateFlow = authViewModel.authEntityStateFlow.collectAsStateWithLifecycle() Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text("authEntityStateFlow: ${authEntityStateFlow.value}") Button(onClick = { authViewModel.authV1() }) { Text("authV1") } Button(onClick = { authViewModel.authV2() }) { Text("authV2") } Button(onClick = { authViewModel.reset() }) { Text("reset") } } }
数据模型类代码
@Serializable data class AuthRespEntity(val data: AuthEntity) @Serializable data class AuthEntity(val token: String)
更新说明
已修改上述代码中被复制的属性。
内容的提问来源于stack exchange,提问作者Patt Mehta
相关产品推荐
相关产品推荐

