Search code examples
androidandroid-lifecycleandroid-architecture-componentsandroid-livedataandroid-jetpack

Android LiveData Observer after onPause


The problem is next, I subscribed to LiveData changes in activity and the first time I'm getting all data in the observer, but when I start another activity and then return to this, the observer not called.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainMenuViewModel.class);

    observeViewModel();
}

@Override
protected void onResume() {
    super.onResume();

    viewModel.loadUserEntry();
}


public void observeViewModel() {

    viewModel.getUser().observe(this, userEntry -> {

        // Do some code 
    });
}

here is code of my ViewModel

void loadUserEntry() {

    disposable.add(userRepository.getUser()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(user::setValue, Throwable::printStackTrace));

}

public LiveData<UserEntry> getUser() {
    return user;
}

So I tested and all-time in subscribe I have user value and then I'm setting this value to the LiveData.

I would appreciate if someone can help with. Thanks.


Solution

  • Take look at paragraph "Observe LiveData objects":

    Generally, LiveData delivers updates only when data changes, and only to active observers. An exception to this behavior is that observers also receive an update when they change from an inactive to an active state. Furthermore, if the observer changes from inactive to active a second time, it only receives an update if the value has changed since the last time it became active.

    I in your case, viewmodel lives as long as activity is in backstack. It lead to LiveData hold instance of UserEntry and when you come back to this activity and call loadUserEntry() it load equal (or even same) instance of UserEntry. Loaded instance is equal to previous one -> LiveData doesn't redeliver it.