I'm implementing LiveData to fetch user data to my ProfileFragment. I store the LiveData variable in ViewModel so that ViewModel doesn't return new LiveData everytime it's called.
However the LiveData doesn't update for the second time, it can display user data in the beginning, but when user edit its data/information, the profile text doesn't update but showing blank text (not showing anything).
I assume this is due to Observer never received the right value, but how can this happened?
ProfileFragment
The viewModel.getUserData
is called on onViewCreated and everytime user finished editing his data/profile information
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider.AndroidViewModelFactory(activity!!.application).create(AboutViewModel::class.java)
viewModel.getUserData()
viewModel.userDataLiveData.observe(viewLifecycleOwner, Observer {
when (it) {
is Resource.Success -> {
text_account_name.text = it.data.name
text_account_email.text = it.data.email
text_account_phone_number.text = it.data.phoneNumber
}
is Resource.Failure -> {
when (it.throwable) {
is UserDataEmptyException -> startFillDataActivity()
}
}
}
})
}
ViewModel
var userDataLiveData: LiveData<Resource<User>> = MutableLiveData()
fun getUserData() {
userDataLiveData = DatabaseRepository.getUserData(uid)
}
DatabaseRepository
fun getUserData(uid: String): LiveData<Resource<User>>{
val result = MutableLiveData<Resource<User>>().apply {
value = Resource.Loading()
}
userRef.child(uid).addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
val name = p0.child(FIELD_NAME).value.toString()
val email = p0.child(FIELD_EMAIL).value.toString()
val phoneNumber = p0.child(FIELD_PHONE_NUMBER).value.toString()
val user = User(name, email, phoneNumber)
if(checkIfUserDataComplete(user)) result.value = Resource.Success(user)
else result.value = Resource.Failure(UserDataEmptyException("User have no data"))
}
override fun onCancelled(p0: DatabaseError) {
result.value = Resource.Failure(p0.toException())
}
})
return result
}