From 7f428a9976f4023a6fdf6ddcf1c4e587cd016cbe Mon Sep 17 00:00:00 2001 From: Vitor Pamplona Date: Thu, 11 Sep 2025 11:05:03 -0400 Subject: [PATCH] Switches account cache to a flow --- .../model/accountsCache/AccountCacheState.kt | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/accountsCache/AccountCacheState.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/accountsCache/AccountCacheState.kt index bf9d40fa6..c23d60820 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/accountsCache/AccountCacheState.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/accountsCache/AccountCacheState.kt @@ -22,7 +22,6 @@ package com.vitorpamplona.amethyst.model.accountsCache import android.content.ContentResolver import android.util.Log -import androidx.collection.LruCache import com.vitorpamplona.amethyst.model.Account import com.vitorpamplona.amethyst.model.AccountSettings import com.vitorpamplona.amethyst.model.LocalCache @@ -40,7 +39,9 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update class AccountCacheState( val geolocationFlow: StateFlow, @@ -49,20 +50,15 @@ class AccountCacheState( val cache: LocalCache, val client: INostrClient, ) { - val accounts = - object : LruCache(20) { - override fun entryRemoved( - evicted: Boolean, - key: HexKey, - oldValue: Account, - newValue: Account?, - ) { - super.entryRemoved(evicted, key, oldValue, newValue) - oldValue.scope.cancel() - } - } + val accounts = MutableStateFlow>(emptyMap()) - fun removeAccount(pubkey: HexKey) = accounts.remove(pubkey) + fun removeAccount(pubkey: HexKey) { + accounts.update { existingAccounts -> + val oldValue = existingAccounts[pubkey] + oldValue?.scope?.cancel() + existingAccounts.minus(pubkey) + } + } fun loadAccount(accountSettings: AccountSettings): Account = loadAccount( @@ -87,7 +83,7 @@ class AccountCacheState( signer: NostrSigner, accountSettings: AccountSettings, ): Account { - val cached = accounts[signer.pubKey] + val cached = accounts.value[signer.pubKey] if (cached != null) return cached return Account( @@ -106,8 +102,19 @@ class AccountCacheState( Log.e("AccountCacheState", "Account ${signer.pubKey} caught exception: ${throwable.message}", throwable) }, ), - ).also { - accounts.put(signer.pubKey, it) + ).also { newAccount -> + accounts.update { existingAccounts -> + existingAccounts.plus(Pair(signer.pubKey, newAccount)) + } + } + } + + fun clear() { + accounts.update { existingAccounts -> + existingAccounts.forEach { + it.value.scope.cancel() + } + emptyMap() } } }