Created
August 11, 2021 18:55
-
-
Save Tetraquark/b5f2f5038aed62c9bd6cab4bb05c0a6b to your computer and use it in GitHub Desktop.
Kotlin multiplatform simple EventBus
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 kotlinx.atomicfu.atomic | |
import kotlinx.atomicfu.getAndUpdate | |
import kotlin.reflect.KClass | |
typealias Observer = (Any) -> Unit | |
object EventBus { | |
private val observers = atomic(mutableMapOf<KClass<out Any>, List<Observer>>()) | |
fun <T : Any> observe(clazz: KClass<T>, obs: (T) -> Unit) { | |
if (!observers.value.containsKey(clazz)) { | |
observers.getAndUpdate { cur -> | |
cur.toMutableMap().also { upd -> | |
upd[clazz] = listOf(obs as Observer) | |
} | |
} | |
} else { | |
observers.getAndUpdate { cur -> | |
cur.toMutableMap().also { upd -> | |
upd[clazz] = upd[clazz]!! + listOf(obs as Observer) | |
} | |
} | |
} | |
} | |
inline fun <reified T : Any> observe(noinline obs: (T) -> Unit) { | |
observe(T::class, obs) | |
} | |
fun <T : Any> removeObserver(clazz: KClass<T>, obs: (T) -> Unit) { | |
observers.getAndUpdate { cur -> | |
cur.toMutableMap().also { upd -> | |
upd.remove(clazz) | |
} | |
} | |
} | |
fun <T : Any> post(clazz: KClass<T>, event: T) { | |
observers.value[clazz]?.forEach { it.invoke(event) } | |
} | |
inline fun <reified T : Any> post(event: T) { | |
post(T::class, event) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment