2017-08-25 23:31:38 +02:00
|
|
|
package exh.util
|
|
|
|
|
|
|
|
|
|
import io.realm.Realm
|
|
|
|
|
import io.realm.RealmModel
|
|
|
|
|
import io.realm.log.RealmLog
|
2020-04-04 22:30:05 +02:00
|
|
|
import java.util.UUID
|
2017-08-25 23:31:38 +02:00
|
|
|
|
|
|
|
|
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
|
2020-04-04 22:30:05 +02:00
|
|
|
} catch (t: Throwable) {
|
2017-11-30 02:35:10 +01:00
|
|
|
if (isInTransaction) {
|
|
|
|
|
cancelTransaction()
|
|
|
|
|
} else {
|
|
|
|
|
RealmLog.warn("Could not cancel transaction, not currently in a transaction.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw t
|
|
|
|
|
} finally {
|
2020-04-04 22:30:05 +02:00
|
|
|
// Just in case
|
2017-11-30 02:35:10 +01:00
|
|
|
if (isInTransaction) {
|
|
|
|
|
cancelTransaction()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-04-14 21:50:05 +02:00
|
|
|
inline fun <T> Realm.useTrans(block: (Realm) -> T): T {
|
|
|
|
|
return use {
|
|
|
|
|
trans {
|
|
|
|
|
block(this)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-04 22:30:05 +02:00
|
|
|
fun <T : RealmModel> Realm.createUUIDObj(clazz: Class<T>) =
|
|
|
|
|
createObject(clazz, UUID.randomUUID().toString())!!
|
2018-04-14 21:50:05 +02:00
|
|
|
|
2020-04-04 22:30:05 +02:00
|
|
|
inline fun <reified T : RealmModel> Realm.createUUIDObj() =
|
2020-05-02 06:46:24 +02:00
|
|
|
createUUIDObj(T::class.java)
|