https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

SecretX

02/26/2021, 6:55 AM
open class Listener<T>(element: T) {
var value: T = element
protected set(value) {
field = value
notifyObservers(field)
}
private val observers: ConcurrentHashMap<UUID, Observer<T>> = ConcurrentHashMap()
private fun notifyObservers(newValue: T) {
observers.forEach { it.value.onChange(newValue) }
}
fun addListener(observer: Observer<T>): Subscription {
var uuid = UUID.randomUUID()
while(observers.contains(uuid)) {
Thread.sleep(1)
uuid = UUID.randomUUID()
}
val subscription = Subscription(uuid, this)
observers[uuid] = observer
return subscription
}
fun unsubscribeListener(uuid: UUID) = observers.remove(uuid)
fun unsubscribeAll(): Int {
val num = observers.size
observers.clear()
return num
}
}
🧵 1
e

ephemient

02/26/2021, 7:29 AM
thread please, and don't dump huge pastes directly into the main chat
Slack has a text snippet option you can use, which will be default-collapsed, or put the paste into the thread
also ``` triple backticks will start and end a code block, just like Markdown, which is better than starting and stopping every individual line with `
2 Views