首页 > 解决方案 > 根据 observable 中的数据更新 UI

问题描述

我的 InfoViewModel 中有 LiveData(用 Java 编写)

public LiveData<List<Info>> getAllInfo(){ return allInfo }

在我的 DashboardActivity(用 Kotlin 编写)中,我试图观察这个 LiveData,然后使用观察者的结果来更新一个列表,该列表又应该更新我的 UI 的一部分。

当 infoList 大小发生变化时要更新的 UI 部分

 if(infoList.isEmpty){ Text("Empty") } else { Text("Info list size is ${InfoList.size} ") }

起初我用

val infoList by remember { mutableStateOf(ArrayList<Info>)}
SideEffect { infoViewModel.allInfo.observe(activity as LifecycleOwner, { infoList.addAll(it) } ) }

但是当观察者更新 infoList 大小时,我的 UI 没有更新。我在这里搜索堆栈溢出并发现

 observeAsState

所以我做了这个

 val infoList by infoViewModel.allInfo.observeAsState

但随后observeAsState 显示错误。我能做些什么。我的主要问题是通知我的 UI 的那部分我的 infoList 已更改,它应该更新自己或至少以任何方式更新我的 UI 相对于 observable

标签: javakotlinandroid-jetpack-compose

解决方案


所以...我后来发现

  observeAsState

是一部分

  androidx.compose.runtime:runtime-livedata

文物所以我添加了

  implementation "androidx.compose.runtime:runtime-livedata:$compose_version"

到我的 build.gradle(应用程序级别)。我还添加了

  implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02'

到我的 build.gradle(应用程序级别),将我的 DAO、存储库和 ViewModel 类从 Java 转换为 Kotlin。在做了所有这些之后,我能够

  import androidx.compose.runtime.livedata.observeAsState

然后在我的 DashboardActivity 上,在我的 @Composable 函数中

  val context = LocalContext.current

  val infoViewModel: InfoViewModel = viewModel(factory = InfoViewModelFactory(context.applicationContext as Application))
  /*this particular type of viewModel(factory = ...) is available after adding implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02' to build.gradle (app level)*/

  val infoList = infoViewModel.allInfo.observeAsState(listOf()).value

然后是当 infoList 大小发生变化时需要更新的 UI 部分

  if(infoList.isEmpty){ Text("Empty") } else { Text("Info list size is ${InfoList.size} ") }

开始完美工作。在本质上,

  implementation "androidx.compose.runtime:runtime-livedata:$compose_version"

                                      ...

  import androidx.compose.runtime.livedata.observeAsState

                                          ...

  val infoList = infoViewModel.allInfo.observeAsState(listOf()).value

为我完成了工作:-)


推荐阅读