简体   繁体   English

番石榴EventBus:没有注释订阅?

[英]Guava EventBus: Subscribe without annotations?

I need to implement a pub/sub system within a domain model. 我需要在域模型中实现pub / sub系统。 I was thinking about using Guava's EventBus, but I'd like to use interfaces and adapters to keep my domain model ignorant of such an implementation detail. 我正在考虑使用Guava的EventBus,但我想使用接口和适配器来保持我的域模型不知道这样的实现细节。 Unfortunately, EventBus's use of annotations for subscription throw a monkey wrench at this idea. 不幸的是,EventBus使用注释进行订阅会给这个想法带来麻烦。

Is there any way to subscribe a handler without using the @Subscribe annotation? 有没有办法在不使用@Subscribe注释的情况下订阅处理程序? Looking at the docs, there doesn't seem to be but perhaps there's something I'm not seeing. 看看文档,似乎没有,但也许有一些我没有看到的东西。

Thanks! 谢谢!

Guava team member here. 番石榴团队成员在这里。

It's quite deliberate that you can only subscribe a handler with the @Subscribe annotation -- EventBus is intended to replace interfaces, adapters, etc., not to supplement them -- but why do you say that exposes more implementation details? 非常谨慎的是你只能使用@Subscribe注释订阅处理程序 - EventBus旨在替换接口,适配器等,而不是补充它们 - 但为什么你说这暴露了更多的实现细节? In our experience, it usually exposes fewer details. 根据我们的经验,它通常会暴露更少的细节。

A workaround is to adapt the Handler. 解决方法是调整Handler。 Something like: 就像是:

class GuavaHandler<T extends Message> implements Handler<T> {
    private Handler<T> handler;

    public GuavaHandler(Handler<T> handler) {
        this.handler = handler;
    }

    @Override
    @Subscribe
    public void handle(T message) {
        try {
            handler.getClass().getMethod("handle", message.getClass());
            handler.handle(message);
        } catch (NoSuchMethodException ignored) {
            // workaround
        }
    }
}

You only define the attribute in this specific implementation. 您只在此特定实现中定义属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM