Last active
February 6, 2016 18:36
-
-
Save dstd/080071b35c2d727673b9 to your computer and use it in GitHub Desktop.
Plain simple events source
This file contains 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
import java.util.* | |
import kotlin.Int | |
import kotlin.Int as ObserverId | |
class Event<T>() { | |
private val listeners: MutableMap<Int, (T) -> Unit> = HashMap(); | |
private var nextListenerId: Int = 0 | |
fun observe(listener: (T) -> Unit): ObserverId { | |
synchronized(this.listeners) { | |
val id = this.nextListenerId++ | |
this.listeners[id] = listener | |
return id | |
} | |
} | |
fun removeObserver(observerId: ObserverId) { | |
synchronized(this.listeners) { | |
this.listeners.remove(observerId) | |
} | |
} | |
fun emit(value: T) { | |
var listeners = synchronized(this.listeners) { ArrayList(this.listeners.values) } | |
for (listener in listeners) | |
listener(value) | |
} | |
} | |
fun test(): Boolean | |
{ | |
val r = StringBuilder() | |
val kbd = Event<Char>() | |
val obs1 = kbd.observe { r.append("1:$it") } | |
kbd.emit('1') | |
val obs2 = kbd.observe { r.append("2:$it") } | |
kbd.emit('2') | |
kbd.emit('3') | |
kbd.removeObserver(obs1) | |
kbd.emit('4') | |
return r.toString() == "1:11:22:21:32:32:4" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment