All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.net.folivo.trixnity.client.store.cache.ConcurrentObservableSet.kt Maven / Gradle / Ivy

There is a newer version: 4.7.1
Show newest version
package net.folivo.trixnity.client.store.cache

import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.map
import net.folivo.trixnity.utils.concurrentOf

class ConcurrentObservableSet(
    initialValue: Set = setOf(),
) {
    private val _values = concurrentOf, MutableSet> { initialValue.toMutableSet() }

    private val changeSignal = MutableSharedFlow(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)

    init {
        changeSignal.tryEmit(Unit)
    }

    val values = changeSignal
        .conflate()
        .map { _values.read { toSet() } }

    suspend fun add(element: T): Boolean = _values.write {
        add(element)
    }.also { if (it) changeSignal.emit(Unit) }

    suspend fun remove(element: T): Boolean = _values.write {
        remove(element)
    }.also { if (it) changeSignal.emit(Unit) }

    suspend fun removeAll() = _values.write {
        clear()
    }.also { changeSignal.emit(Unit) }

    suspend fun size(): Int = _values.read { size }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy