Iam trying to learn jetpack compose. Iam stuck with the ViewModels.
I have a ViewModel
class DataViewModel: ViewModel() {
//the list of live data
var listData = mutableListOf<Data>()
//initialize the viewmodel
init {
viewModelScope.launch {
//do the network call (this is working ok)
val data = fetchData()
data.forEach {
listData.add(it)
//print the list of data, this is working fine
println("listData")
}
}
}
So fetching the data and put it in the dataList is working fine. But no i want to display the data on my screen. I made a composable
@Composable
//pass in the viewmodel
fun DataScreen(model:DataViewModel = viewModel()){
println("model.listData")
this return an empty list ?
Column{
model.listData?.forEach { item ->
Text("${item}")
}
}
}
On my screen nothing happens because its an empty list in the composable. How can i get the list from the ViewModel ?
CodePudding user response:
The problem is you do not use State value in your view model. State is needed in order to register your value for Composable recomposition (in case the value is assigned/changed)
So You need to have View Model like this (I guess your fetchData is a suspend function):
class DataViewModel: ViewModel() {
//the list of live data
val listDataState = MutableState<List<Data>> = mutableStateOf(emptyList<Data>())
//initialize the viewmodel
init {
viewModelScope.launch {
val data = fetchData()
listDataState.value = data
}
}
suspend fun fetchData() : List<Data>{
//something like:
return dataRepository.getData()
}
}
Then in your @Composable function you get the data like this:
val viewModel: DataViewModel = viewModel()
val data = viewModel.listDataState.value