Search code examples
androidviewmodelandroid-livedataobserver-pattern

ViewModel does not trigger observer of mutablelivedata


I have the following ViewModel class -

class VerifyOtpViewModel : ViewModel() {

    private var existingUserProfileData: MutableLiveData<TwoVerteUsers.TwoVerteUser>? = null

    fun checkInfoForAuthenticatedUser(authorization: String, user: String) {
        ProfileNetworking.getUsersProfiles(authorization, GetUserProfilesBodyModel(listOf(user)), object : ProfileNetworking.OnGetUserProfilesListener {
            override fun onSuccess(model: TwoVerteUsers) {
                existingUserProfileData?.value = model[0]
            }

            override fun onError(reason: String) {
                Log.d("existingProfile", reason)
            }
        })
    }

    fun getExistingUserProfileData(): LiveData<TwoVerteUsers.TwoVerteUser>? {
        if (existingUserProfileData == null) return null
        return existingUserProfileData as LiveData<TwoVerteUsers.TwoVerteUser>
    }
}

and the following observer -

private fun initViewModel() {
        verifyOtpViewModel = ViewModelProvider(this).get(VerifyOtpViewModel::class.java)
        verifyOtpViewModel.getExistingUserProfileData()?.observe(this, Observer {
            if (it != null)
                Log.d("existingProfile", it.username)
        })
    }

For some reason the observe is never triggered even after the MutableLiveData object is being given a value

Tried to search for a solution here at stackoverflow but nothing helped

what am I missing?


Solution

  • refactor your code to this, and you should be good to go:

    class VerifyOtpViewModel : ViewModel() {
    
        private val _existingUserProfileData = MutableLiveData<TwoVerteUsers.TwoVerteUser>()
        val existingUserProfileData: LiveData<TwoVerteUsers.TwoVerteUser>
            get() = _existingUserProfileData
    
        fun checkInfoForAuthenticatedUser(authorization: String, user: String) {
            ProfileNetworking.getUsersProfiles(
                authorization,
                GetUserProfilesBodyModel(listOf(user)),
                object : ProfileNetworking.OnGetUserProfilesListener {
                    override fun onSuccess(model: TwoVerteUsers) {
                        existingUserProfileData.value = model[0]
                    }
    
                    override fun onError(reason: String) {
                        Log.d("existingProfile", reason)
                    }
                })
        }
    }
    

    And observing:

    verifyOtpViewModel.existingUserProfileData.observe(this, Observer {
       .....
    })