First of all, this works 100% fine, but i feel like there is a better way, and maybe im not fully understanding the mutablelive data – observable conection, Although works fine..
ViewModel is doing the work, but the observe part is correct? Ignore retrofit plz.
@Composable
fun layoutX(){
val news = remember { mutableStateOf( ArrayList<BasicCardNews>()) } //ignore 'by'
//... here i do the ui layout with rows cols and boxes and some part i got this
getLazyColumnNews(mainActivity, news)//another composable function
...
}
@Composable
fun getLazyColumnNews(....) {
val appViewModel = viewModel(AppViewModel::class.java) //just to get the vm ref
appViewModel.startRetrofitCall() //getting the json as pojos
appViewModel.news.observe(context,{ // im observing news in vm and update news.value
news.value = appViewModel.getNews().value as ArrayList<BasicCardNoticia>
})
LazyColumn(
contentPadding = PaddingValues(...)
) {
//So news.value starts with 0 elemenst but updated when we observer change
items(news.value) {
getCardNoticia(info = it) // just mapping
Spacer(...)
}
}
//And the viewmodel that makes the call:
fun startCall(){
...//retrofit stuff
viewModelScope.launch(Dispatchers.IO) {
val response = apiCall.getRepoNews(UtilsStrings.urlResolve).awaitResponse()
if (response.isSuccessful){
// ... i mapped values to a new list so i can do this.
news.value = newListX
}
//last in view model this variable
var news = MutableLiveData<ArrayList<BasicCardNews>>()
fun getNews():LiveData<ArrayList<BasicCardNoticia>>{
return alNews
}
This sums up a way to consume a rest using retrofit, coroutines, with compose.. but feels like a hack.. what is wrong with this please ??