-
-
Save rovkinmax/d86ca5d70637c83f945b39f18e889af4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object RealmProvider { | |
fun provideRealm(): Realm { | |
return Realm.getDefaultInstance() | |
} | |
fun <T : RealmModel> queryFromRealm(func: (Realm) -> T?): Observable<T> { | |
return queryFromRealmFlowable(func).toObservable() | |
} | |
fun <T : RealmModel> queryFromRealmFlowable(func: (Realm) -> T?): Flowable<T> { | |
return Flowable.defer<T> { | |
val realm = Realm.getDefaultInstance() | |
try { | |
realm.beginTransaction() | |
val result = func(realm) | |
var resultCloned: T? = null | |
if (RealmObject.isValid(result)) { | |
resultCloned = realm.copyFromRealm(result) | |
} | |
realm.commitTransaction() | |
if (resultCloned == null) { | |
return@defer Flowable.empty() | |
} else | |
return@defer Flowable.just<T>(resultCloned) | |
} catch (e: Exception) { | |
realm.cancelTransaction() | |
Flowable.error<T>(e) | |
} finally { | |
realm.close() | |
} | |
} | |
} | |
fun <T : RealmModel> queryListFromRealm(func: (Realm) -> List<T>): Single<List<T>> { | |
return Single.defer<List<T>> { | |
val realm = Realm.getDefaultInstance() | |
try { | |
realm.beginTransaction() | |
val result = func(realm) | |
val resultCloned = result.map { realm.copyFromRealm(it) } | |
realm.commitTransaction() | |
return@defer Single.just<List<T>>(resultCloned) | |
} catch (e: Exception) { | |
realm.cancelTransaction() | |
Single.error<List<T>>(e) | |
} finally { | |
realm.close() | |
} | |
} | |
} | |
} | |
fun <T : RealmModel> Observable<T>.queryFromRealm(func: (T, Realm) -> T?): Observable<T> { | |
return flatMap { result -> RealmProvider.queryFromRealm { realm -> func(result, realm) } } | |
} | |
fun <T : RealmModel> Single<List<T>>.queryFromRealm(func: (List<T>, Realm) -> List<T>): Single<List<T>> { | |
return flatMap { result -> RealmProvider.queryListFromRealm { realm -> func(result, realm) } } | |
} | |
fun <T : RealmModel> Flowable<T>.queryFromRealm(func: (T, Realm) -> T?): Flowable<T> { | |
return flatMap { result -> RealmProvider.queryFromRealmFlowable { realm -> func(result, realm) } } | |
} | |
fun Realm.executeClosableTransaction(transaction: (Realm) -> Unit): Unit { | |
try { | |
beginTransaction() | |
transaction(this) | |
commitTransaction() | |
} catch (e: Exception) { | |
Timber.tag(this.javaClass.simpleName).d(e, "Can't execute transaction") | |
cancelTransaction() | |
} finally { | |
close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment