Created
August 17, 2018 05:07
-
-
Save mcmatan/1673096f246709777d008a83b5e13da6 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
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) { | |
//1 | |
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()) { | |
//2 | |
realm?.close() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment