Skip to content Skip to sidebar Skip to footer

Why Does My Activity Doesn't See An Observed Object Change?

I'm new to Android development and i am trying to understand Live Data with MVVM architecture. I am trying to make the main activity recognize when there is a change in an object t

Solution 1:

here your problem is with repository code inside repository you are creating new object of mutable live data and observing different one.

InterfaceCallback{
    onSuccess(String response)
    onError(String error)
}

publicvoidlogin(String username , String hashedPassword,Callback callback){
    final MutableLiveData<String> loggedInUser = newMutableLiveData<>();
    User user = newUser(username,hashedPassword);

    usersRepositoryApi.login(user).enqueue(newCallback<String>() {
        @OverridepublicvoidonResponse(Call<String> call, Response<String> response) {
            if (response.isSuccessful()) {
                callback.onSuccess(response.body());
            }
        }

        @OverridepublicvoidonFailure(Call<String> call, Throwable t) {
            callback.onError(null);
        }
    });
}
//login method of your viewmodel publicvoidlogin(String userName , String hashedPassword) {
     usersRepository.login(userName, hashedPassword,newCallback(){
          voidonSuccess(String responsebody){
               loggedInUser.setValue(responsebody);
          }

          voidonError(String error){
               loggedInUser.setValue(responsebody);
          }
     });
}

Solution 2:

In your repository, try changing this part:

loggedInUser.setValue(response.body());

to postValue function. like that:

loggedInUser.postValue(response.body());

Post a Comment for "Why Does My Activity Doesn't See An Observed Object Change?"