Skip to content

Instantly share code, notes, and snippets.

@ZherebtsovAlexandr
Last active September 14, 2018 14:57
Show Gist options
  • Save ZherebtsovAlexandr/db2d1ab490d8816e94302821db4ffa1d to your computer and use it in GitHub Desktop.
Save ZherebtsovAlexandr/db2d1ab490d8816e94302821db4ffa1d to your computer and use it in GitHub Desktop.
Integration Realm DataBase и kotlinx.coroutines
fun getData() = produce<List<Data>>(LooperThread) {
var results = realm.where(Data::class.java).findAll()
send(map(results))
results.addChangeListener { results ->
run {
launch(LooperThread) {
send(map(results))
}
}
}
}
//Rx version used Observable default library implementation like
override fun <E : RealmModel> from(realm: Realm, results: RealmResults<E>): Observable<RealmResults<E>> {
val realmConfig = realm.configuration
return Observable.create { subscriber ->
val observableRealm = Realm.getInstance(realmConfig)
resultsRefs.get().acquireReference(results)
val listener = RealmChangeListener<RealmResults<E>> {
if (!subscriber.isUnsubscribed) {
subscriber.onNext(results)
}
}
results.addChangeListener(listener)
subscriber.add(Subscriptions.create {
results.removeChangeListener(listener)
observableRealm.close()
resultsRefs.get().releaseReference(results)
})
subscriber.onNext(results)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment