1

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

看起来 unregister 方法只将订阅者作为参数,而不是事件。

我知道我可以为每个事件使用不同的实例,但这并不是真正可扩展的。

我也检查了 Otto,但看起来你也不能从特定事件中取消注册。

任何帮助,将不胜感激。

谢谢

4

1 回答 1

0

您可以将此方法添加到 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);
    }
}

这允许取消注册特定的事件类型,如下所示:

EventBus.getDefault().unregister(this, MyEvent.class);

附录

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

/**
 * @deprecated For simplification of the API, this method will be removed in the future.
 */
@Deprecated
public synchronized void unregister(Object subscriber, Class<?>... eventTypes)
于 2015-03-18T16:53:06.680 回答