您的位置:首页 > 其它

EventBus源码阅读(4)-Subscription

2016-08-09 14:14 344 查看
在使用EventBus的时候,我们首先要注册(EventBus.register),还要编写相应的消息响应函数(onMainThreadEvent)

在EventBUs的不同版本中,有不同的注册响应函数的方法,老版本是通过函数名识别的,所以函数名称只能为既定的几种形式(例如onMainThreadEvent),但我们现在分析的版本是通过注释的方式进行识别的(@Subscribe)

该类描述的是一条订阅记录,即我们注册的一个类似于onEventMainThread(Event)的函数。

我们在应用的代码中写一条类似于onMainThreadEvent(Event)的函数(早期版本,现在的版本只需要添加@Subscribe注释即可),机会生成一条这样的记录。

源码:

/*
* Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0 *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.greenrobot.eventbus;

final class Subscription {
final Object subscriber;//订阅者(经常是Activity实例)
final SubscriberMethod subscriberMethod;//订阅的方法
/**
* Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery
* {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions.
*/
volatile boolean active;

Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
this.subscriber = subscriber;
this.subscriberMethod = subscriberMethod;
active = true;
}

@Override
public boolean equals(Object other) {
if (other instanceof Subscription) {
Subscription otherSubscription = (Subscription) other;
return subscriber == otherSubscription.subscriber
&& subscriberMethod.equals(otherSubscription.subscriberMethod);
} else {
return false;
}
}

@Override
public int hashCode() {
return subscriber.hashCode() + subscriberMethod.methodString.hashCode();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: