EventBus源码解析04-取消订阅

时间:2021-03-08 14:44:20

取消订阅会调用unregister()

public synchronized void unregister(Object subscriber) {
//根据subscriber获取eventType集合
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
//遍历eventType集合
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}

可以看到,这里会根据subscriber获取eventType集合,再遍历这个集合逐个调用unsubscribeByEventType

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//根据eventType获取Subscription(被观察者)集合
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
//遍历subscriptions集合
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
//判断subscriber是否相同
if (subscription.subscriber == subscriber) {
subscription.active = false;
//移除被观察者
subscriptions.remove(i);
i--;
size--;
}
}
}
}

这里,会根据eventType获取Subscription(被观察者)集合,在遍历subscriptions集合,找到和传入的subscriber相同的对象,将其从subscriptions集合中移除,从而取消订阅。

总结

EventBus的取消订阅主要就是根据传入的subscriber,把相应的被观察者(Subscription)从subscriptions集合(之前注册的时候所存放的集合)中移除。

final class Subscription {
//@Subscribe所在的类
final Object subscriber;
//@Subscribe注解的方法
final SubscriberMethod subscriberMethod;
}