Android EventBus-从特定事件注销

Android EventBus-从特定事件注销,android,publish-subscribe,greenrobot-eventbus,Android,Publish Subscribe,Greenrobot Eventbus,我在Android应用程序中使用EventBus,我试图从特定事件中注销,同时继续注册到其他事件 看起来unregister方法只将订阅服务器作为参数,而不将事件作为参数 我知道我可以为每个事件使用不同的实例,但这不是真正的可伸缩性 我也检查了Otto,但看起来你也无法从特定事件中注销 任何帮助都将不胜感激 谢谢您可以将此方法添加到EventBus类中: /** * Unregisters the given subscriber from a specific event class. *

我在Android应用程序中使用EventBus,我试图从特定事件中注销,同时继续注册到其他事件

看起来unregister方法只将订阅服务器作为参数,而不将事件作为参数

我知道我可以为每个事件使用不同的实例,但这不是真正的可伸缩性

我也检查了Otto,但看起来你也无法从特定事件中注销

任何帮助都将不胜感激


谢谢

您可以将此方法添加到EventBus类中:

/**
 * Unregisters the given subscriber from a specific event class.
 */
public synchronized void unregister(Object subscriber, Class<?> eventType) {
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null && subscribedTypes.contains(eventType)) {
        unubscribeByEventType(subscriber, eventType);
        subscribedTypes.remove(eventType);
        if (subscribedTypes.isEmpty() {
            typesBySubscriber.remove(subscriber);
        }
    } else {
        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass() + " / " + eventType);
    }
}
附录

我刚刚发现有一种现有的方法可以做到这一点,尽管它已被弃用:

/**
 * @deprecated For simplification of the API, this method will be removed in the future.
 */
@Deprecated
public synchronized void unregister(Object subscriber, Class<?>... eventTypes)

这两个图书馆都没有这个概念。只需保留一个布尔值IsThisEventSomethingToOrryAbout,并在执行业务逻辑之前在事件处理程序方法中检查它,当你在相同的条件下切换布尔值,直到你从这个特定事件中注销时。考虑切换到RXJava或通用的反应方法,知道这个方法,我不明白他们为什么想要贬低它。因为我只想从特定事件注册,所以我为该事件创建了单独的EventBus实例。我对这种方法不满意,但这将暂时奏效。
/**
 * @deprecated For simplification of the API, this method will be removed in the future.
 */
@Deprecated
public synchronized void unregister(Object subscriber, Class<?>... eventTypes)