I have LiveData in my InfoViewModel (written in Java)
public LiveData<List<Info>> getAllInfo(){ return allInfo }
In my DashboardActivity (written in Kotlin) i am trying to observe this LiveData then use result from the observer to update a list which should in turn update a portion of my UI.
The portion of my UI to be updated when there is a change in infoList size
if(infoList.isEmpty){ Text("Empty") } else { Text("Info list size is ${InfoList.size} ") }
At first i used
val infoList by remember { mutableStateOf(ArrayList<Info>)}
SideEffect { infoViewModel.allInfo.observe(activity as LifecycleOwner, { infoList.addAll(it) } ) }
But my UI did not update when infoList size was updated by the observer. I searched here on stack overflow and found
observeAsState
So i did this
val infoList by infoViewModel.allInfo.observeAsState
But then observeAsState show errors. What can i do. My main problem here is notifying that portion of my UI that my infoList has changed and it should update itself or at least any way to update my UI with respect to the observable
So... I later discovered that
observeAsState
Is part of the
androidx.compose.runtime:runtime-livedata
artifacts so i added
implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
to my build.gradle (app level). I also added
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02'
to my build.gradle (app level), converted my DAO, repository and ViewModel classes from Java to Kotlin. After doing all these, i was able to
import androidx.compose.runtime.livedata.observeAsState
Then on my DashboardActivity, inside my @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
Then the portion of my UI that needed to be updated when there is a change in infoList size
if(infoList.isEmpty){ Text("Empty") } else { Text("Info list size is ${InfoList.size} ") }
Started to work perfectly. In essence,
implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
...
import androidx.compose.runtime.livedata.observeAsState
...
val infoList = infoViewModel.allInfo.observeAsState(listOf()).value
got the job done for me:-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.