ViewModel 不会触发 mutablelivedata 的观察者

ViewModel does not trigger observer of mutablelivedata

我有以下 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>
    }
}

和以下观察者 -

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

出于某种原因,即使在为 MutableLiveData 对象赋值后,也永远不会触发观察

试图在 Whosebug 上搜索解决方案,但无济于事

我错过了什么?

重构你的代码,你应该可以开始了:

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

观察:

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