Jetpack 使用 Coroutine's StateFlow 组成



我在使用Jetpack Compose的StateFlow时遇到了一个奇怪的问题,在那里我没有收到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"))

my 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项目:

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

class MainViewModel : ViewModel() {
val homeViewModel get() = HomeViewModel()
fun getListOfNames(){
homeViewModel.getList()
}
}

最新更新