ViewModel выполняет всю работу , но часть наблюдения верна? Не обращайте внимания на модернизацию.
Код: Выделить всё
@Composable
fun layoutX(){
val news = remember { mutableStateOf( ArrayList()) } //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
})
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()
fun getNews():LiveData{
return alNews
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... mvvm-compo
Мобильная версия