I am new to jetpack compose. I have this value which is a MutableLiveData. I want ofc to observe on the object and get the value. I was wondering if i could convert the MutableLiveData to MutableState in an easy way? To make it even simpler, or is it best to keep it as a MutableLiveData?
Asked
Active
Viewed 2,372 times
1
-
1No it is better to use `MutableState` instead of `LiveData` if your app is fully built in Compose. – Richard Onslow Roper Nov 18 '21 at 08:55
-
Why even declare it as a `MutableLiveData` object? Just initialize it as `val a by mutableStateOf(/*You Data Here*/)`. What's the issue? It can be used even in the `ViewModel` – Richard Onslow Roper Nov 18 '21 at 08:56
-
Add more details about the use case maybe to get a better approach if any. Otherwise, accept Abhimanyu's answer. It is the actual way to convert it. – Richard Onslow Roper Nov 18 '21 at 08:57
1 Answers
3
Use observeAsState()
to convert LiveData
to State
.
Use LiveData
in ViewModel
, Repository
and other layers.
Convert and observe it using observeAsState()
in the Composable.
Example code
val itemState by viewModel.itemsLiveData.observeAsState()

Abhimanyu
- 11,351
- 7
- 51
- 121
-
If you do this, remember to add this dependency: `implementation ("androidx.compose.runtime:runtime-livedata:1.4.0")` – Joaquin Iurchuk Mar 27 '23 at 03:58