Skip to content

Instantly share code, notes, and snippets.

@mcmatan
Created August 17, 2018 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcmatan/3d66aa2338b4f247e9de74486e26e319 to your computer and use it in GitHub Desktop.
Save mcmatan/3d66aa2338b4f247e9de74486e26e319 to your computer and use it in GitHub Desktop.
class RealmLock {
private var _uiRealm: Realm? = null
fun getRealm(runningFromTransaction: Boolean = false): Realm {
return if (MainThread.isMainThread()) {
if (_uiRealm == null) {
_uiRealm = Realm.getDefaultInstance()
}
_uiRealm!!
} else {
if (!runningFromTransaction) {
ExceptionThrower.trow("Getting realm instance on back thread must happen only from within transaction")
}
Realm.getDefaultInstance()
}
}
fun transaction(block: (realm: Realm) -> Unit) {
var realm: Realm? = null
try {
realm = this.getRealm(true)
realm.executeTransaction {
block(it)
}
} finally {
if (!MainThread.isMainThread()) {
realm?.close()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment