簡體   English   中英

根據 observable 中的數據更新 UI

[英]Update UI with respect to data from observable

我的 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 function

  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

為我完成了工作:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM