Better transitions to a Nostrclient that is autocloseable, destroying all links to everything else when closing

This commit is contained in:
Vitor Pamplona
2026-03-22 11:16:54 -04:00
parent 459f69ff2c
commit adb3a0e0fc
4 changed files with 28 additions and 1 deletions
@@ -41,6 +41,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.IO
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
@@ -77,12 +78,15 @@ import kotlinx.coroutines.launch
*/
class NostrClient(
private val websocketBuilder: WebsocketBuilder,
private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()),
private val parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()),
) : INostrClient,
IRelayClientListener,
AutoCloseable {
private val relayPool: RelayPool = RelayPool(websocketBuilder, this)
/** Scope for all subscriptions. */
private val scope = CoroutineScope(parentScope.coroutineContext + SupervisorJob())
private val activeRequests: PoolRequests = PoolRequests()
private val activeCounts: PoolCounts = PoolCounts()
private val eventOutbox: PoolEventOutbox = PoolEventOutbox()
@@ -330,5 +334,10 @@ class NostrClient(
override fun close() {
disconnect()
listeners = emptySet()
activeCounts.destroy()
activeRequests.destroy()
eventOutbox.destroy()
scope.cancel()
}
}
@@ -213,4 +213,10 @@ class PoolCounts {
) {
// mark as impossible to get count from this relay
}
fun destroy() {
relayState.clear()
relays.tryEmit(emptySet())
queries.clear()
}
}
@@ -188,4 +188,9 @@ class PoolEventOutbox {
}
}
}
fun destroy() {
eventOutbox = emptyMap()
relays.tryEmit(emptySet())
}
}
@@ -333,4 +333,11 @@ class PoolRequests {
// They are the same don't do anything.
}
}
fun destroy() {
relayState.clear()
desiredSubs.clear()
desiredSubListeners.clear()
desiredRelays.tryEmit(emptySet())
}
}