Migrating the NostrDataSource to Atomic Boolean

This commit is contained in:
Vitor Pamplona
2023-02-28 19:52:16 -05:00
parent 95423bdd94
commit df43e730ca

View File

@@ -17,11 +17,14 @@ import com.vitorpamplona.amethyst.service.relays.Subscription
import com.vitorpamplona.amethyst.service.relays.hasValidSignature import com.vitorpamplona.amethyst.service.relays.hasValidSignature
import java.util.Date import java.util.Date
import java.util.UUID import java.util.UUID
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import nostr.postr.events.ContactListEvent import nostr.postr.events.ContactListEvent
import nostr.postr.events.DeletionEvent import nostr.postr.events.DeletionEvent
import nostr.postr.events.Event import nostr.postr.events.Event
@@ -42,6 +45,7 @@ abstract class NostrDataSource(val debugName: String) {
} }
} }
private val clientListener = object : Client.Listener() { private val clientListener = object : Client.Listener() {
override fun onEvent(event: Event, subscriptionId: String, relay: Relay) { override fun onEvent(event: Event, subscriptionId: String, relay: Relay) {
if (subscriptionId in subscriptions.keys) { if (subscriptionId in subscriptions.keys) {
@@ -91,7 +95,6 @@ abstract class NostrDataSource(val debugName: String) {
} catch (e: Exception) { } catch (e: Exception) {
e.printStackTrace() e.printStackTrace()
} }
} }
} }
@@ -146,17 +149,24 @@ abstract class NostrDataSource(val debugName: String) {
subscriptions = subscriptions.minus(subscription.id) subscriptions = subscriptions.minus(subscription.id)
} }
var handlerWaiting = false // Refreshes observers in batches.
@Synchronized var handlerWaiting = AtomicBoolean()
fun invalidateFilters() {
if (handlerWaiting) return fun invalidateFilters() {
if (handlerWaiting.getAndSet(true)) return
println("DataSource: ${this.javaClass.simpleName} InvalidateFilters")
handlerWaiting = true
val scope = CoroutineScope(Job() + Dispatchers.IO) val scope = CoroutineScope(Job() + Dispatchers.IO)
scope.launch { scope.launch {
delay(200) try {
resetFiltersSuspend() delay(200)
handlerWaiting = false resetFiltersSuspend()
} finally {
withContext(NonCancellable) {
handlerWaiting.set(false)
}
}
} }
} }