komikku/app/src/main/java/exh/util/RealmUtil.kt

46 lines
988 B
Kotlin
Raw Normal View History

2017-08-25 23:31:38 +02:00
package exh.util
import io.realm.Realm
import io.realm.RealmModel
import io.realm.log.RealmLog
import java.util.*
inline fun <T> realmTrans(block: (Realm) -> T): T {
return defRealm {
2017-11-30 02:35:10 +01:00
it.trans {
block(it)
2017-08-25 23:31:38 +02:00
}
}
}
inline fun <T> defRealm(block: (Realm) -> T): T {
return Realm.getDefaultInstance().use {
block(it)
}
}
2017-11-30 02:35:10 +01:00
inline fun <T> Realm.trans(block: () -> T): T {
beginTransaction()
try {
val res = block()
commitTransaction()
return res
} catch(t: Throwable) {
if (isInTransaction) {
cancelTransaction()
} else {
RealmLog.warn("Could not cancel transaction, not currently in a transaction.")
}
throw t
} finally {
//Just in case
if (isInTransaction) {
cancelTransaction()
}
}
}
2017-08-25 23:31:38 +02:00
fun <T : RealmModel> Realm.createUUIDObj(clazz: Class<T>)
2017-11-30 02:35:10 +01:00
= createObject(clazz, UUID.randomUUID().toString())!!