Switches account cache to a flow

This commit is contained in:
Vitor Pamplona
2025-09-11 11:05:03 -04:00
parent 4347a1b104
commit 7f428a9976

View File

@@ -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<LocationState.LocationResult>,
@@ -49,20 +50,15 @@ class AccountCacheState(
val cache: LocalCache,
val client: INostrClient,
) {
val accounts =
object : LruCache<HexKey, Account>(20) {
override fun entryRemoved(
evicted: Boolean,
key: HexKey,
oldValue: Account,
newValue: Account?,
) {
super.entryRemoved(evicted, key, oldValue, newValue)
oldValue.scope.cancel()
}
}
val accounts = MutableStateFlow<Map<HexKey, Account>>(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()
}
}
}