事件的 Otto 事件总线运行时订阅

Otto event bus runtime subscription for events

是否可以在 Otto 中订阅事件而不使用 @Subscribe 注释?

在我的用例中,我不知道我的对象应该在编译时订阅哪个事件。我希望根据某些规则在运行时执行此操作。

我想你可以使用这样的解决方法,

public class MainClass {    

    private EventObserver eventObserver;

    public MainClass() {
        if(...someCondition...) {
            eventObserver = new FirstEventObserver();
        } else {
            eventObserver = new SecondEventObserver();
        }
    }

    public onEvent(Event event) {
        if (event instanceOf FirstEvent) {
            ... handle event ...
        } else if (event instanceOf SecondEvent) {
            ... handle event ...
        }
    }
}

public abstract class EventObserver {

    protected MainClass mainClass;

    public void setMainClass(MainClass mainClass) {
        this.mainClass = mainClass;
    }

    protected void notifyMainClass(Event event) {
        if (mainClass != null) {
            mainClass.onEvent(event);
        }
    }
}

public class FirstEventObserver extends EventObserver {

    public FirstEventObserver() {
        bus.subscribe(this);
    }

    @Subscribe
    public void onEvent(FirstEvent event) {
        notifyMainClass();
    }
}


public class SecondEventObserver extends EventObserver {

    public SecondEventObserver() {
        bus.subscribe(this);
    }

    @Subscribe
    public void onEvent(SecondEvent event) {
        notifyMainClass();
    }
}

public abstract class Event {
}

public abstract class FirstEvent extends Event {
}

public abstract class SecondEvent extends Event {
}

另一种解决方法,这是一种更简洁的解决方案。您可以在运行时生成您想要的类型的事件。

public class MainClass {
    @Subscribe
    public void onEvent(Event event) {
        if (event.getType() == EventType.FIRST_EVENT) {
            ... handle event ...
        } else if (event.getType() == EventType.SECOND_EVENT) {
            ... handle event ...
        }
    }
}

public class Event {
    public enum EventType {
        FIRST_EVENT,
        SECOND_EVENT
    }

    private EventType eventType;

    public Event(EventType eventType) {
        this.eventType = eventType;
    }

    public EventType getType() {
        return eventType;
    }
}

我使用 Otto 创建了一个用于在运行时订阅事件的框架。可以为不同的事件使用不同的 EventDelegate,而不是为不同的事件类型使用不同的模型 类。这些事件委托将只接收事件并将它们传递给订阅者 类。 典型的 EventDelegate 看起来像这样

public abstract class OttoEventDelegate {
private OttoEventListener ottoEventListener;

public OttoEventDelegate(OttoEventListener ottoEventListener) {
    this.ottoEventListener = ottoEventListener;
}

public void register() {
    BaseApplication.getInstance().getBus().register(this);
}

public void unregister() {
    BaseApplication.getInstance().getBus().unregister(this);
}

public OttoEventListener getOttoEventListener() {
    return ottoEventListener;
}

public void setOttoEventListener(OttoEventListener ottoEventListener) {
    this.ottoEventListener = ottoEventListener;
}
}

此方法已解释 in this article. Also if you want to have a look at implementation. Its on github here