java - 根据 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
解决方案
所以...我后来发现
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
为我完成了工作:-)
推荐阅读
- javascript - Lite-server 无法启动,原因是“Unexpected token ...”
- c++ - 存储字符串文字指针是否安全?
- python - 寻找一种简化的方法来计算数组之间的成对相关性
- java - 没有比较器的java 8 Hashmap中的红黑树实现
- angular - 错误 TS2769:没有重载匹配此调用。键入'字符串 | null' 不可分配给类型 'string | 细绳[]'
- javascript - Javascript 添加年初至今并输入 html 输入
- mysql - 设置休眠 GenerationType.IDENTITY 的初始值
- amazon-web-services - 有没有办法知道 AWS AppConfig 中更新的配置?
- c++ - 循环在单链表节点创建中无限执行
- java - SQL Anywhere 批处理操作