observeAsState not working for list, in jetpack compose

Viewed 1996

I am trying to display a list of objects in a composable. for that i am having a viewmodel with below list variable

var allProviders: LiveData<MutableList<ServiceProvider>> = MutableLiveData(mutableListOf())

also, on view model init, i am calling an api to populate above list as:-

private fun getAllMerchantList() {
    getAllMerchants(object: RetrofitCallback {
        override fun onData(data: Any?) {
            //some logic here
            allProviders.value?.addAll(allProvidersLocal)
            Log.i("TAG", "ServiceProviders inside: ${allProviders.value?.size}")
        }

        override fun onFailed(ex: String?) {
            Log.i("TAG", "onFailed: ${ex.toString()}")
        }
    })
}

And, observing above, in composable, like:-

val viewModel: MainActivityViewModel = viewModel()
val allProviders by viewModel.allProviders.observeAsState()

but, above code is not working. Its always returning empty list in composable. But if i log through viewmodel function, i can see the data. How can i correct this?

2 Answers

Use mutableStateListOf instead of LiveData in Compose

var allProviders by mutableStateListOf<ServiceProvider>()

Now use it as a regular list object. It will trigger recompositions. Also, as far as possible use MutableState type objects in Compose since they are built for it, and vice versa.

You can also use

val mutableStateFlod: MutableStateFlow<MutableList<ServiceProvider>> = MutableStateFlow(emptyList())

instead ov LiveData and all

collectAsState
Related