Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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, transaction: Realm.Transaction): Unit = suspendCancellableCoroutine { continuation ->
- try {
- transaction.execute(realm)
- continuation.resume(Unit)
- } catch (e: Exception) {
- continuation.resumeWithException(e)
- }
- }
- suspend fun <S: RealmObject> RealmQuery<S>.await() = findAllAwait(this)
- suspend fun <S: RealmObject> RealmQuery<S>.awaitFirst() = findFirstAwait(this)
- suspend fun Realm.transactAwait(transaction: Realm.Transaction) = executeAsync(this, transaction)
- 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)
- })
- }
- }
Add Comment
Please, Sign In to add comment