gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:45:24 26 4
gpt4 key购买 nike

是否可以在 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;
}
}

关于android - 事件的 Otto 事件总线运行时订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37839074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com