我正在使用 Jetpack compose 进行 UI 渲染。我有 Fragment1 和 Fragment2。我有一个在活动范围中定义的 viewModel SharedViewModel 。
当我通过 SharedViewModel 从前台的 Fragment2 发送更新时,它不会更新位于后台的 Fragment1,它正在观察 SharedViewModel 的状态对象。
活动->
private val viewModel: SharedViewModel by viewModels { viewModelFactory }
共享视图模型->
private val _installedApps = MutableStateFlow(HashMap<String, String>())
val installedApps: StateFlow<Map<String, String>> = _installedApps.asStateFlow()
fun updateInstalledApps(appId: String, params: String) {
_installedApps.update {
it[appId] = params
it
}
}
片段1 ->
fun ListScreen(
listViewModel: ListViewModel,
viewModel: SharedViewModel,
onBackButtonClicked: () -> Unit
) {
val state by appListViewModel.appListState.collectAsState()
val context = LocalContext.current
LaunchedEffect(inContextStoreViewModel.installedApps.collectAsState().value) {
appListViewModel.updateInstalledApps(inContextStoreViewModel.installedApps.value)
}
LaunchedEffect(inContextStoreViewModel.networkConnectionState.collectAsState().value) {
if (state.apps.isEmpty()) {
appListViewModel.getApps(appAcquisitionParams, inContextStoreViewModel.launchParamsObject.value)
}
}
// rest of UI which is observing
}
片段2 ->
onAddClicked = {
detailViewModel.install(
callBack = {
sharedViewModel.updateInstalledApps(appId, it)
}
)
},
有趣的是,网络连接状态总是在所有片段中正确更新,因为它是从活动触发的。此外,当使用导航图时,这工作得很好。但对于 Fragment Transaction,它导致了这个问题。 需要一些关于 viewModel 概念被遗漏的输入。
StateFlow
不会触发收集器。您正在更新哈希图中的一个项目并返回相同的StateFlow
。无法检测到地图等复杂结构内部的变化。因为只是比较像StateFlow == StateFlow
。如果属实,收藏家就不火了。
或者每次调用
updateInstalledApps
时创建新的 hashmap,或者使用 SharedFlow
代替(内部没有比较)。