Skip to content

Instantly share code, notes, and snippets.

@michaelbukachi
Last active May 24, 2022 04:31
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelbukachi/0c7f18bdeaf4bdb12b5527304d6cdbc0 to your computer and use it in GitHub Desktop.
Save michaelbukachi/0c7f18bdeaf4bdb12b5527304d6cdbc0 to your computer and use it in GitHub Desktop.
Realm Coroutines
import io.realm.*
import io.realm.kotlin.where
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
private suspend fun <T: RealmObject, S: RealmQuery<T>> findAllAwait(query: S): RealmResults<T> = suspendCancellableCoroutine { continuation ->
val listener = RealmChangeListener<RealmResults<T>> { t -> continuation.resume(t) }
query.findAllAsync().addChangeListener(listener)
}
private suspend fun <T: RealmObject, S: RealmQuery<T>> findFirstAwait(query: S): T? = suspendCancellableCoroutine { continuation ->
val listener = RealmChangeListener { t: T? -> continuation.resume(t) }
query.findFirstAsync().addChangeListener(listener)
}
private suspend fun executeAsync(realm: Realm, block: (Realm) -> Unit): Unit = suspendCancellableCoroutine { continuation ->
realm.executeTransactionAsync({ block(it) }, { continuation.resume(Unit) }, { continuation.resumeWithException(it) })
}
suspend fun <S: RealmObject> RealmQuery<S>.await() = findAllAwait(this)
suspend fun <S: RealmObject> RealmQuery<S>.awaitFirst() = findFirstAwait(this)
suspend fun Realm.transactAwait(block: (Realm) -> Unit) = executeAsync(this, block)
class TestObject(val name: String? = "") : RealmObject()
fun test() {
GlobalScope.launch {
val realm = Realm.getDefaultInstance()
val result = realm.where<TestObject>().awaitFirst()
val results = realm.where<TestObject>().await()
realm.transactAwait(Realm.Transaction {
val testObject = TestObject(name = "Some Test")
it.copyToRealm(testObject)
})
}
}
@michaelbukachi
Copy link
Author

Hi @kibotu. Thanks for pointing that out. It's important do cleanup after cancellation. Also, I created a library for this at https://github.com/michaelbukachi/realm-koroutines. Would nice if you could raise an issue over there.

@kibotu
Copy link

kibotu commented Mar 3, 2020

cool thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment