Guest User

Untitled

a guest
Dec 10th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. import io.realm.*
  2. import io.realm.kotlin.where
  3. import kotlinx.coroutines.GlobalScope
  4. import kotlinx.coroutines.launch
  5. import kotlinx.coroutines.suspendCancellableCoroutine
  6. import kotlin.coroutines.resume
  7. import kotlin.coroutines.resumeWithException
  8.  
  9. private suspend fun <T: RealmObject, S: RealmQuery<T>> findAllAwait(query: S): RealmResults<T> = suspendCancellableCoroutine { continuation ->
  10. val listener = RealmChangeListener<RealmResults<T>> { t -> continuation.resume(t) }
  11. query.findAllAsync().addChangeListener(listener)
  12. }
  13.  
  14. private suspend fun <T: RealmObject, S: RealmQuery<T>> findFirstAwait(query: S): T? = suspendCancellableCoroutine { continuation ->
  15. val listener = RealmChangeListener { t: T? -> continuation.resume(t) }
  16. query.findFirstAsync().addChangeListener(listener)
  17. }
  18.  
  19. private suspend fun executeAsync(realm: Realm, transaction: Realm.Transaction): Unit = suspendCancellableCoroutine { continuation ->
  20. try {
  21. transaction.execute(realm)
  22. continuation.resume(Unit)
  23. } catch (e: Exception) {
  24. continuation.resumeWithException(e)
  25. }
  26. }
  27.  
  28. suspend fun <S: RealmObject> RealmQuery<S>.await() = findAllAwait(this)
  29.  
  30. suspend fun <S: RealmObject> RealmQuery<S>.awaitFirst() = findFirstAwait(this)
  31.  
  32. suspend fun Realm.transactAwait(transaction: Realm.Transaction) = executeAsync(this, transaction)
  33.  
  34. class TestObject(val name: String? = "") : RealmObject()
  35.  
  36. fun test() {
  37. GlobalScope.launch {
  38. val realm = Realm.getDefaultInstance()
  39. val result = realm.where<TestObject>().awaitFirst()
  40. val results = realm.where<TestObject>().await()
  41. realm.transactAwait(Realm.Transaction {
  42. val testObject = TestObject(name = "Some Test")
  43. it.copyToRealm(testObject)
  44. })
  45. }
  46. }
Add Comment
Please, Sign In to add comment