Home > front end >  How can I track liveData subscription?
How can I track liveData subscription?

Time:12-17

I have a problem with liveData. It doesn't update the fragment with the information. I think it unsubscribes from viewLifecycleOwner at some particular moment. Is there a way to track the subscription of liveData and see if it unsubscribes or not? Thank you!

Fragment

    val loginResult: MutableLiveData<RequestResult<LoginResponse>> by lazy {
        MutableLiveData()
    }
            
            
             vm.loginRequestResult.observe(viewLifecycleOwner) {
                when (it) {
                    is RequestResult.Success -> vm.navigateToSetLocation()
                    is RequestResult.Error -> showErrorIncorrectEmailOrPassword()
                }
            }

Viewmodel:

        when(response){
            is RequestResult.Success ->  loginRequestResult.value = response
            is RequestResult.Error -> loginRequestResult.postValue(response)
        }

CodePudding user response:

You defined your LiveData instance inside your Fragment. Fragment instances can be torn down and recreated by the OS under many events. If this happens, your LiveData instance will be a new one with no memory from the old one. Probably you are going to some other screen for your login event, and when it returns to your Fragment, it is a new Fragment instance.

This is the reason ViewModel was created. It outlives the recreations of your Fragment. You must define your LiveData inside the ViewModel, not the Fragment. If you are not backing up the value to disk, you should at least back up the value using SavedInstanceState to cover cases where your Fragment is restored after your app is suspended for low memory reasons.

CodePudding user response:

You should move your LiveData into ViewModel

  • Related