Jetpack Compose 无法观察 MutableLiveData。

huangapple go评论61阅读模式
英文:

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() }
    }
}

huangapple
  • 本文由 发表于 2023年5月11日 19:04:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定