ViewModel不会触发mutablelivedata的观察者

时间:2020-04-26 07:38:44

标签: android viewmodel android-livedata observer-pattern

我有以下ViewModel类-

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对象赋予值之后,也不会触发观察

试图在stackoverflow上搜索解决方案,但没有帮助

我想念什么?

1 个答案:

答案 0 :(得分:1)

将代码重构为此,您应该会很高兴:

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