英文:
Jetpack Compose can't observe MutableLiveData
问题
viewModel.todoLists.observe(lifecycleOwner) {
it?.let { label.value = it.toString() }
}
英文:
View
viewModel.todoLists.observe(lifecycleOwner){
it?.let { label.value = it.toString() }
}
ViewModel
val todoLists : MutableLiveData <ListResponse> = MutableLiveData()
fun getTodoList() {
viewModelScope.launch {
try {
val response = api.getTodos("Bearer ${jwt.value.toString()}")
if (response.isSuccessful) {
val list = response.body()!!
todoLists.value = list // it works
}
} catch (e: Exception) {
e.message?.let {
Log.d("Login TLVM", it)
}
}
}
}
I can fetch data in ViewModel, but I cannot get data from the LiveData in the View. What should I do?
答案1
得分: 0
You should use provided observeAsState() extension function to observe LiveData from compose. It will look like this:
val list = viewModel.todoLists.observeAsState()
Now list always has the most recent value of viewModel.todoLists. When you set a new value inside your ViewModel, your composable will recompose to use that new value.
If you want to add an observer to your LiveData instead, you have to do so inside of LaunchedEffect:
LaunchedEffect(viewModel) {
viewModel.todoLists.observe(lifecycleOwner) {
it?.let { label.value = it.toString() }
}
}
英文:
You should use provided observeAsState() extension function to observe LiveData from compose. It will look like this:
val list = viewModel.todoLists.observeAsState()
Now list always has the most recent value of viewModel.todoLists. When you set new value inside of your ViewModel, your composable will recompose to use that new value.
If you would want to add observer to your LiveData instead, you have to do so inside of LaunchedEffect:
LaunchedEffect(viewModel) {
viewModel.todoLists.observe(lifecycleOwner){
it?.let { label.value = it.toString() }
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论