JetpackCompose与Coroutine的StateFlow

我在使用 StateFlow 和 Jetpack Compose 时遇到了一个奇怪的问题,我没有收到 StateFlow 中的更新值。这是我如何按照示例中的建议尝试观察 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)
        }
    }
}

}

我正确收到初始值但没有收到更新值

setContent {
  Surface(color = MaterialTheme.colors.background) {
                List(mainViewModel.homeViewModel)
      }
}

我已经像这样在 viewModel 中定义了我的 stateFlow

internal val stateFlow = MutableStateFlow(AppState())

我通过这个更新值

stateFlow.value = AppState(loading = false, listOf("1", "2"))

我的 AppState Pojo

data class AppState(val names: List<Names> = emptyList(), val isLoading: Boolean = true, val error: Throwable? = null)

问题是当我像上面那样更新 stateFlow 的值时,我希望可组合重新组合并更新值,但更新后的值永远不会出现在我上面的可组合方法中。我需要一些帮助来了解我哪里出错了

PS:我还没有在 LiveData 上试过这个

回答

基于你在 twitter 上提到的https://github.com/cyph3rcod3r/D-KMP-Architecture项目:

问题是在下面的代码中,HomeViewModel每次调用 getter 时都会创建一个新实例,这homeViewModel.stateFlow意味着您正在观察和正在更新的实例是不同的。

class MainViewModel : ViewModel() {
     val homeViewModel get() = HomeViewModel()

    fun getListOfNames(){
        homeViewModel.getList()
    }
}

  • -_- So silly of me to miss out this. Thanks a lot @john for pointing this out, removing get() from variable worked fine. Thanks for the community support

以上是JetpackCompose与Coroutine的StateFlow的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>