1

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)
        }
Alex20280
  • 97
  • 6
  • Where is `loginRequestResult` defined, in the ViewModel? Also, when are you setting up the observer, is it in the `onViewCreated()` of the fragment? – JTODR Dec 16 '22 at 17:38
  • Yes, in onViewCreated() and yes, loginRequestResult is defined in ViewModel. – Alex20280 Dec 16 '22 at 17:44
  • Can you update your answer to show the definition of `loginRequestResult` in your ViewModel. – JTODR Dec 16 '22 at 17:46
  • Sorry, maybe I misunderstand. I included the declaration of loginRequestResult in the fragment. – Alex20280 Dec 16 '22 at 17:58

2 Answers2

1

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.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
1

You should move your LiveData into ViewModel