From 790cbb35db9d170dca3e8c9e2ffe5b79efa820c6 Mon Sep 17 00:00:00 2001 From: Vitor Pamplona Date: Tue, 14 Feb 2023 09:29:24 -0500 Subject: [PATCH] Moving Database updates to an invalidate UI call that only runs at every 100 ms. --- .../amethyst/model/LocalCache.kt | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/vitorpamplona/amethyst/model/LocalCache.kt b/app/src/main/java/com/vitorpamplona/amethyst/model/LocalCache.kt index 87d95204a..e9e1f6ecd 100644 --- a/app/src/main/java/com/vitorpamplona/amethyst/model/LocalCache.kt +++ b/app/src/main/java/com/vitorpamplona/amethyst/model/LocalCache.kt @@ -22,6 +22,12 @@ import java.time.format.DateTimeFormatter import java.util.Collections import java.util.concurrent.ConcurrentHashMap import com.vitorpamplona.amethyst.service.relays.Relay +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import nostr.postr.events.ContactListEvent import nostr.postr.events.DeletionEvent import nostr.postr.events.Event @@ -502,12 +508,30 @@ object LocalCache { val live: LocalCacheLiveData = LocalCacheLiveData(this) private fun refreshObservers() { - live.refresh() + live.invalidateData() } } class LocalCacheLiveData(val cache: LocalCache): LiveData(LocalCacheState(cache)) { - fun refresh() { + + // Refreshes observers in batches. + var handlerWaiting = AtomicBoolean() + + @Synchronized + fun invalidateData() { + if (!hasActiveObservers()) return + if (handlerWaiting.getAndSet(true)) return + + handlerWaiting.set(true) + val scope = CoroutineScope(Job() + Dispatchers.Main) + scope.launch { + delay(100) + refresh() + handlerWaiting.set(false) + } + } + + private fun refresh() { postValue(LocalCacheState(cache)) } }