EventBus源碼筆記

執(zhí)行的線程呻引,優(yōu)先級,是否是粘性時間 @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = true)
1 注冊:
EventBus.Register(this);
2解綁:
EventBus.unRegister(this);
3接收

@Subscribe
public void func(eventBean event) {}

4發(fā)送

EventBus.post

register(obj) :
遍歷傳入的 class的所有方法枉长,找到有Subscribe注解的所有方法 返回一個list

 public void register(Object subscriber) {   
 Class<?> subscriberClass = subscriber.getClass(); 
   List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) { 
           subscribe(subscriber, subscriberMethod);?
        }
    }
}

findUsingReflectionInSingleClass 第一步:解析注冊者對象的所有方法玉转,并且找出帶有注解subscribe注解的方法荚板,然后通過annotation解析所有細(xì)節(jié)參數(shù)址遇, 封裝成一個對象,添加到集合滋戳,返回钻蔑。

 findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,        subscribeAnnotation.priority(), subscribeAnnotation.sticky()));

先從緩存中取
如果緩存中沒有
ignoreGeneratedIndex:是否忽略注解生成器的MyEventBusIndex 默認(rèn)false
默認(rèn)走注解生成器
如果獲取的列表為空,拋出異常
否則 返回list

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }

    if (ignoreGeneratedIndex) {
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        subscriberMethods = findUsingInfo(subscriberClass);
    }
    if (subscriberMethods.isEmpty()) {
        throw new EventBusException("Subscriber " + subscriberClass
                + " and its super classes have no public methods with the @Subscribe annotation");
    } else {
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    }
}

findUsingReflectionInSingleClass 核心方法

private void findUsingReflectionInSingleClass(FindState findState) {
    Method[] methods;
    try {
        // This is faster than getMethods, especially when subscribers are fat classes like Activities
        methods = findState.clazz.getDeclaredMethods();          //獲取所有方法
    } catch (Throwable th) {
        // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
        methods = findState.clazz.getMethods();
        findState.skipSuperClasses = true;
    }
    for (Method method : methods) {
        int modifiers = method.getModifiers();
        if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
                    Class<?> eventType = parameterTypes[0];
                    if (findState.checkAdd(method, eventType)) {
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                    }
                }
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException("@Subscribe method " + methodName +
                        "must have exactly 1 parameter but has " + parameterTypes.length);
            }
        } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
            String methodName = method.getDeclaringClass().getName() + "." + method.getName();
            throw new EventBusException(methodName +
                    " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
        }
    }
}
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
    List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
    findState.recycle();
    synchronized (FIND_STATE_POOL) {
        for (int i = 0; i < POOL_SIZE; i++) {
            if (FIND_STATE_POOL[i] == null) {
                FIND_STATE_POOL[i] = findState;
                break;
            }
        }
    }
    return subscriberMethods;
}

最終裝入緩存池奸鸯,并返回對象

//—  .method.getParameterTypes  獲取參數(shù)列表 
//method.setAccessible(true);  似有方法需要執(zhí)行這句
Class a = Client.class;
try {
    Method method = a.getDeclaredMethod("a", int.class, int.class);
    System.out.println("----"+method.getParameterTypes().length + "-------“);//2
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

第二步:
subscribe() 解析所有SubscriberMethod的eventType,然后按照要求解析成
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType的格式咪笑,
key是eventType
value就是subscription的列表,subscription包含兩個對象的封裝
如下

final class Subscription {
    final Object subscriber;//
    final SubscriberMethod subscriberMethod;//
    娄涩。窗怒。。
}

所以最終形成的map結(jié)構(gòu)是這樣:

    @Subscribe
    public void onRefresh(EventB event) {
    }
/*
subscriptionsByEventType 的key   就是  EventB.class   
Subscription  中的參數(shù)分別對應(yīng)的 方法依托的類  蓄拣,以及具體的方法
*/
  synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //eventType是方法參數(shù)的class
        Class<?> eventType = subscriberMethod.eventType;
        //再次封裝對象扬虚,一個Subscription,對象中存入  :eg:activity實例弯蚜,第二個是解析好的被注解的那個方法
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //subscriptionsByEventType 
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);//一個map  key:對應(yīng)的類    a
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                // Existing sticky events of all subclasses of eventType have to be considered.
                // Note: Iterating over all events may be inefficient with lots of sticky events,
                // thus data structure should be changed to allow a more efficient lookup
                // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
                Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry<Class<?>, Object> entry : entries) {
                    Class<?> candidateEventType = entry.getKey();
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

post源碼分析:待續(xù)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市剃法,隨后出現(xiàn)的幾起案子碎捺,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件收厨,死亡現(xiàn)場離奇詭異晋柱,居然都是意外死亡,警方通過查閱死者的電腦和手機诵叁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進店門雁竞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人拧额,你說我怎么就攤上這事碑诉。” “怎么了侥锦?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵进栽,是天一觀的道長。 經(jīng)常有香客問我恭垦,道長快毛,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任番挺,我火速辦了婚禮唠帝,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘玄柏。我一直安慰自己襟衰,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布禁荸。 她就那樣靜靜地躺著右蒲,像睡著了一般。 火紅的嫁衣襯著肌膚如雪赶熟。 梳的紋絲不亂的頭發(fā)上瑰妄,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天,我揣著相機與錄音映砖,去河邊找鬼间坐。 笑死,一個胖子當(dāng)著我的面吹牛邑退,可吹牛的內(nèi)容都是我干的竹宋。 我是一名探鬼主播,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼地技,長吁一口氣:“原來是場噩夢啊……” “哼蜈七!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起莫矗,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤飒硅,失蹤者是張志新(化名)和其女友劉穎砂缩,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體三娩,經(jīng)...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡庵芭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了雀监。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片双吆。...
    茶點故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖会前,靈堂內(nèi)的尸體忽然破棺而出好乐,到底是詐尸還是另有隱情,我是刑警寧澤回官,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布曹宴,位于F島的核電站,受9級特大地震影響歉提,放射性物質(zhì)發(fā)生泄漏笛坦。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一苔巨、第九天 我趴在偏房一處隱蔽的房頂上張望版扩。 院中可真熱鬧,春花似錦侄泽、人聲如沸礁芦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽柿扣。三九已至,卻和暖如春闺魏,著一層夾襖步出監(jiān)牢的瞬間未状,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工析桥, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留司草,地道東北人。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓泡仗,卻偏偏與公主長得像埋虹,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子娩怎,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,066評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 對于Android開發(fā)老司機來說肯定不會陌生搔课,它是一個基于觀察者模式的事件發(fā)布/訂閱框架,開發(fā)者可以通過極少的代碼...
    飛揚小米閱讀 1,478評論 0 50
  • 我每周會寫一篇源代碼分析的文章,以后也可能會有其他主題.如果你喜歡我寫的文章的話,歡迎關(guān)注我的新浪微博@達達達達s...
    SkyKai閱讀 24,934評論 23 184
  • 博文出處:EventBus源碼解析截亦,歡迎大家關(guān)注我的博客爬泥,謝謝旦事! 0001B 時近年末,但是也沒閑著急灭。最近正好在看...
    俞其榮閱讀 1,301評論 1 16
  • 原文鏈接:http://blog.csdn.net/u012810020/article/details/7005...
    tinyjoy閱讀 547評論 1 5
  • EventBus地址:https://github.com/greenrobot/EventBus 一、event...
    君莫看閱讀 1,995評論 2 11