Load maxValue in KeyManager lazily

This commit is contained in:
Moez Bhatti
2018-06-09 00:24:24 -04:00
parent 010fcdccb1
commit d4093cc8ff
+10 -7
View File
@@ -26,18 +26,14 @@ import javax.inject.Singleton
@Singleton
class KeyManagerImpl @Inject constructor() : KeyManager {
private var maxValue: Long = 0L
init {
val realm = Realm.getDefaultInstance()
maxValue = realm.where(Message::class.java).max("id")?.toLong() ?: 0L
realm.close()
}
private var initialized = false
private var maxValue: Long = 0
/**
* Should be called when a new sync is being started
*/
override fun reset() {
initialized = true
maxValue = 0L
}
@@ -45,6 +41,13 @@ class KeyManagerImpl @Inject constructor() : KeyManager {
* Returns a valid ID that can be used to store a new message
*/
override fun newId(): Long {
if (!initialized) {
maxValue = Realm.getDefaultInstance().use { realm ->
realm.where(Message::class.java).max("id")?.toLong() ?: 0L
}
initialized = true
}
maxValue++
return maxValue
}