Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afaucogney/26d5b8bfd123d16fc6f2497e2f35a341 to your computer and use it in GitHub Desktop.
Save afaucogney/26d5b8bfd123d16fc6f2497e2f35a341 to your computer and use it in GitHub Desktop.
LiveRealmData.kt
/**
* 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()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment