Removing Observers in Android LiveData and ViewModel

Published by inkskull on

Removing Observers in Android LiveData and ViewModel

Removing Observers in Android LiveData and ViewModel

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

Check google developers page for more info 

 

The advantages of using LiveData

  1. Ensures your UI matches your data state
  2. No memory leaks
  3. No crashes due to stopped activities
  4. No more manual lifecycle handling
  5. Always up to date data
  6. Proper configuration changes
  7. Sharing resources

You can register an observer without an associated LifecycleOwner object using the observeForever(Observer) method. In this case, the observer is considered to be always active and is therefore always notified about modifications. You can remove these observers calling theremoveObserver(Observer) method.

 

Create a ViewModel

/**
 * View model class
 */
public class SchoolViewModel extends AndroidViewModel {
    //live school data
    public final LiveData<List<School>> schoolLiveData;
    private RoomDatabase mDatabase;

    public SchoolViewModel(@NonNull Application application) {
        super(application);
        mDatabase = RoomDatabase.getDatabase(this.getApplication());
        this.schoolLiveData = mDatabase.schoolDao().getAllSchoolsLive();
    }

    public LiveData<List<School>> getSchoolLiveData() {
        return schoolLiveData;
    }

    public void AddSchoolData(int count) {

        School school = new School(count, String.format(Locale.getDefault(),"School %d", count), String.format(Locale.getDefault(),"School Address %d", count), "2222222222");
        mDatabase.schoolDao().insertSchool(school);
    }
}
Adding Observer OR Subscribing ViewModel

To observe a LiveData,call observe(LifecycleOwner, Observer<T>) or observeForever(Observer<T>).

observe(LifecycleOwner, Observer<T>): This is the standard way to observe a LiveData. It ties the observer to a Lifecycle, changing LiveData‘s active and inactive state according to the LifecycleOwner current state.

 

private SchoolViewModel mSchoolViewModel;

mSchoolViewModel = ViewModelProviders.of(this).get(SchoolViewModel.class);
mSchoolViewModel.getSchoolLiveData().observe(MainActivity.this, new Observer<List<School>>() {
    @Override
    public void onChanged(@Nullable List<School> schools) {
        Log.d(TAG, "onChanged() called with: schools = [" + schools + "]");
        showSchoolData(schools);
    }
});
Removing  Observer
private SchoolViewModel mSchoolViewModel;
if (mSchoolViewModel != null && mSchoolViewModel.getSchoolLiveData().hasObservers()) {
    mSchoolViewModel.getSchoolLiveData().removeObservers(this);
}

We need to pass lifecycle owner to removeObservers(LifeCycleOwner)  like above

mSchoolViewModel.getSchoolLiveData().removeObservers(this);

 

You can get the full source code from GitHub

 

 

 

Categories: RxJava2

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Media Auto Publish Powered By : XYZScripts.com