Last active
March 23, 2021 13:14
-
-
Save SecretX33/ea78ebf755c6e9984aff234a1f30d586 to your computer and use it in GitHub Desktop.
Listener (without synchronization)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open class Listener<T>(element: T) { | |
var value: T = element | |
protected set(value) { | |
field = value | |
notifyObservers(field) | |
} | |
private val observers: MutableMap<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.putIfAbsent(uuid, observer) != null) { | |
Thread.sleep(1) | |
uuid = UUID.randomUUID() | |
} | |
val subscription = Subscription(uuid, this) | |
return subscription | |
} | |
fun unsubscribeListener(uuid: UUID) = observers.remove(uuid) | |
fun unsubscribeAll() = observers.clear() | |
} | |
class MutableListener<T>(element: T) : Listener<T>(element) { | |
fun set(value: T) { super.value = value } | |
} | |
fun interface Observer<T> { | |
fun onChange(newValue: T) | |
} | |
class Subscription(private val uuid: UUID, listener: Listener<*>) { | |
private var listener: Listener<*>? = listener | |
fun dispose() { | |
listener?.unsubscribeListener(uuid) | |
listener = null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Listener is read only
If you want to change the value, declare it as or cast it to MutableListener