[英]Jetpack Compose with Coroutine's StateFlow
I am running into a strange issue while using StateFlow with Jetpack Compose, where I am not receiving the updated value in the StateFlow.我在使用带有 Jetpack Compose 的 StateFlow 时遇到了一个奇怪的问题,我没有收到 StateFlow 中的更新值。 This is the code how I try to observe the Stateflow as suggested in the examples.
这是我尝试按照示例中的建议观察 Stateflow 的代码。
@Composable
fun List(homeViewModel: HomeViewModel) {
val appState by homeViewModel.stateFlow.collectAsState()
if (appState.isLoading) {
CircularProgressIndicator()
}
MaterialTheme {
LazyColumn {
items(appState.names) { name ->
Name(name = name.name)
}
}
}
} }
I receive the initial value correctly but not the updated value我正确收到初始值,但没有收到更新值
setContent {
Surface(color = MaterialTheme.colors.background) {
List(mainViewModel.homeViewModel)
}
}
I have defined my stateFlow in the viewModel like this我已经像这样在 viewModel 中定义了我的 stateFlow
internal val stateFlow = MutableStateFlow(AppState())
I update the value by this我通过这个更新值
stateFlow.value = AppState(loading = false, listOf("1", "2"))
my AppState Pojo我的 AppState Pojo
data class AppState(val names: List<Names> = emptyList(), val isLoading: Boolean = true, val error: Throwable? = null)
The problem is when I update the value of stateFlow like above I expect the composable to recompose and update the value but the updated value never comes to my composable method above.问题是当我像上面那样更新 stateFlow 的值时,我希望可组合组件能够重新组合和更新该值,但更新的值永远不会出现在我上面的可组合方法中。 I need a little help on where I am going wrong
我需要一点帮助来解决我哪里出错了
PS: I haven't tried this on LiveData yet
PS:我还没有在 LiveData 上尝试过这个
Going on basis of https://github.com/cyph3rcod3r/D-KMP-Architecture project you mentioned on twitter:基于您在 twitter 上提到的https://github.com/cyph3rcod3r/D-KMP-Architecture项目:
Issue is that in following code a new instance of HomeViewModel
is being created each time getter is called meaning that homeViewModel.stateFlow
that you're observing and instance that you're updating are different.问题是,在以下代码中,每次调用 getter 时都会创建一个新的
HomeViewModel
实例,这意味着您正在观察的homeViewModel.stateFlow
和正在更新的实例是不同的。
class MainViewModel : ViewModel() {
val homeViewModel get() = HomeViewModel()
fun getListOfNames(){
homeViewModel.getList()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.