Skip to content

事件总线

事件模块提供轻量级发布/订阅机制。事件只需实现 rain.api.event.Event

定义事件

kotlin
data class UserCreated(val userId: Long) : Event

监听事件

kotlin
@EventListener
class UserEventListener {
    @SubscribeEvent
    fun onUserCreated(event: UserCreated) {
        println(event.userId)
    }
}

监听器类必须是可由 DI 容器创建的 Bean,并位于扫描包内。监听方法会在加载阶段注册。

发布事件

kotlin
class UserService(
    private val eventBus: EventBus,
) {
    fun create() {
        eventBus.post(UserCreated(42))
    }
}

监听权重

@SubscribeEvent(weight = ...) 支持以下顺序等级:

LOWESTLOWNORMALHIGHHIGHESTRECORD

返回值 Boolean 由事件总线实现定义;可取消事件可基于 CancelAbleEvent / AbstractCancelAbleEvent 扩展。

基于 Apache License 2.0 发布