Last active
July 26, 2021 06:52
-
-
Save Zhuinden/7d49a2b136f6f478de09f0e79f4b0e0b to your computer and use it in GitHub Desktop.
Architectural Components: Realm in ViewModel (based on https://github.com/googlesamples/android-architecture-components/blob/178fe541643adb122d2a8925cf61a21950a4611c/BasicSample/app/src/main/java/com/example/android/persistence/viewmodel/ProductListViewModel.java )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// based on https://github.com/googlesamples/android-architecture-components/blob/178fe541643adb122d2a8925cf61a21950a4611c/BasicSample/app/src/main/java/com/example/android/persistence/viewmodel/ProductListViewModel.java | |
public class ProductListViewModel { | |
private final MutableLiveData<List<ProductEntity>> observableProducts = new MutableLiveData<>(); | |
Realm realm; | |
RealmResults<ProductEntity> results; | |
RealmChangeListener<RealmResults<ProductEntity>> realmChangeListener = (results) -> { | |
if(results.isLoaded() && results.isValid()) { | |
observableProducts.setValue(results); | |
} | |
}; | |
public ProductListViewModel() { | |
realm = Realm.getDefaultInstance(); | |
// previously: final DatabaseCreator databaseCreator = | |
// DatabaseCreator.getInstance(this.getApplication()); | |
observableProducts.setValue(null); // if using async query API, the change listener will set the loaded results. | |
results = realm.where(ProductEntity.class).findAllSortedAsync("id"); // this could be from dao instead | |
results.addChangeListener(realmChangeListener); | |
} | |
public LiveData<List<ProductEntity>> getProducts() { | |
return observableProducts; | |
} | |
@Override | |
protected void onCleared() { | |
results.removeChangeListener(realmChangeListener); | |
realm.close(); | |
realm = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment