I am trying to store the data in mutableStateOf() to view it in my compose function, I receive the response in my variable and assign it to State<List?> but in my compose function I recieve no data at all, yet the init block in viewmodel when I debug showes that my data is recieved? I dont understand how MutablStates works and why it doesn't function like Live data? and if it doesn't functions like LiveData what is its alternative in JetPack compose
Here is my code in my Viewmodel
private var _categoryItems = mutableStateOf<List<Data>?>(emptyList())
val categoryItems : State<List<Data>?> = _categoryItems
init {
val service = RetrofitInstance.getRetrofitInstance().create(IGetBusinessCategory::class.java)
viewModelScope.launch {
var logText = ""
logText = service.getBusinessCategory().toString()
val categoryItems = service.getBusinessCategory().body()!!.data
Log.v("CategoryItems", logText)
_categoryItems = mutableStateOf(categoryItems)
}
}
}
and here how I try to get the data in my Compose Screen
val businessCategoryModel = BusiniessCategoryViewModel()
val listOfCategories by rememberSaveable { businessCategoryModel.categoryItems }
Yet when I debug I recieve no items at all in listOfCategories while its recieved in _categoryItems in the viewmodel, so how can I get the functionality of livedata with states in compose? is this even possiable?
CodePudding user response:
Instead of:
_categoryItems = mutableStateOf(categoryItems)
Try this:
_categoryItems.value = categoryItems
Also, instead of:
val listOfCategories by rememberSaveable { businessCategoryModel.categoryItems }
Try this:
val listOfCategories by remember { mutableStateOf(businessCategoryModel.categoryItems) }