Last active
February 20, 2021 18:24
-
-
Save cmelchior/3fe791f84db37fd3bcb3749d4188168a to your computer and use it in GitHub Desktop.
LiveRealmData.kt
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
/** | |
* Class connecting the Realm lifecycle to that of LiveData objects. | |
* Realm will remain open for as long as any LiveData objects are being observed. | |
*/ | |
abstract class LiveRealmData<T: RealmModel>(val config: RealmConfiguration) : LiveData<RealmResults<T>>() { | |
private val listener = RealmChangeListener<RealmResults<T>> { results -> value = results } | |
private lateinit var realm: Realm | |
private var results: RealmResults<T>? = null | |
override final fun onActive() { | |
realm = Realm.getInstance(config) | |
results = runQuery(realm); | |
results.addChangeListener(listener) | |
value = results; | |
} | |
override final fun onInactive() { | |
results!!.removeAllChangeListeners() | |
results = null | |
realm.close() | |
} | |
abstract fun runQuery(realm: Realm): RealmResults<T> | |
} | |
fun usage() : LiveData<RealmResults<Person>> { | |
return object: LiveRealmData<Person>(getConfig()) { | |
override fun runQuery(realm: Realm): RealmResults<Person> { | |
// Called on UI thread | |
return realm.where(Person::class.java).findAllAsync() | |
} | |
} | |
} |
public LiveRealmData(RealmResults realmResults) {
results = realmResults;
setValue(results);
}
setValue() should be called in the constructor.
@suryachintu + 1
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, if you only use
async
queries, that will work as well. The ViewModel becomes responsible for theRealm
lifecycle, but neither looks wrong to me. If the ViewModel uses the Realm for other things (which is probably likely), then your approach looks cleaner.You can then argue if you should call
setValue()
with the unloadedRealmResults
in the constructor or not. Bot have their use cases I guess.