我的目标是在Kotlin中实现非常简单的事件总线,而无需任何第三方库。我用下面的代码实现了这一点。
class EventListener<T>(
val owner: Any,
val event: Class<T>,
val callback: (T) -> Unit
)
interface IEventBus {
fun <T> subscribe(owner: Any, event: Class<T>, callback: (T) -> Unit)
fun unsubscribe(owner: Any)
fun <T> push(event: T)
}
class EventBus : IEventBus {
private val _listeners = mutableListOf<EventListener<*>>()
override fun <T> subscribe(owner: Any, event: Class<T>, callback: (T) -> Unit) {
val listener = EventListener(owner, event, callback)
_listeners.add(listener)
}
override fun unsubscribe(owner: Any) {
_listeners.removeAll {
it.owner == owner
}
}
override fun <T> push(event: T) {
_listeners.forEach { listener ->
try {
val l = listener as EventListener<T> // is always a success
l.callback(event) // throws an exception if can't handle the event
} catch (ex: Exception) { }
}
}
}
然后用法如下:
// register listener
bus.subscribe(this, String::class.java) {
print(it)
}
// push an event (from somewhere else in the project)
bus.push("Hello world!")
它可以工作并且完全可用,但是我对此并不满意...将侦听器转换为EventListener总是会返回某些内容,然后如果l.callback(event)无法处理事件类型,它将抛出异常。因此,如果订阅了许多侦听器,则它将生成许多不需要的异常,这些异常将被忽略。
我希望先进行某种检查,例如:
if (listener is EventListener<T>)
listener.callback(event)
但是我发现JVM在编译后会丢失有关泛型类型的信息。我还发现可以使用kotlin的inline和reified绕过它,但是不能在来自接口的方法上使用它们。
所以我的问题是,您是否知道任何更优雅的方式来处理此类通用问题?
由于您已经公开了事件的类(EventListener#event
),因此可以isInstance()
用来检查该类是否与事件的实例兼容。
因此,代替:
if (listener is EventListener<T>)
listener.callback(event)
你可以做:
if (listener.event.isInstance(event)) {
// The cast is safe since you checked if the event can be received by the listener.
(listener as EventListener<T>).callback(event)
}
原语
如果你想支持T
与基本类型也一样,你可以改变Class<T>
到KClass<T>
或手动检查实例上的每个基本类型(例如event is Int
,event is Long
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句