手寫EventBus框架——動手_終結(jié)

路漫漫其修遠兮

01. 手寫EventBus框架——源碼分析1
02. 手寫EventBus框架——源碼分析2
03. 手寫EventBus框架——動手_整體架構(gòu)設(shè)計
04. 手寫EventBus框架——動手_終結(jié)


上一篇文章已經(jīng)把我們的整體架構(gòu)已經(jīng)搭建好了,實現(xiàn)原理和技術(shù)在我們分析源碼的時候也已經(jīng)知道,現(xiàn)在我們來實現(xiàn)它吧。

先實現(xiàn)我們的工具類;

SubscriberMethodFinder.class

/**
 * 訂閱方法查找類
 * <p/>
 * Author: 溫利東 on 2017/3/26 11:21.
 * blog: http://www.reibang.com/u/99f514ea81b3
 * github: https://github.com/LidongWen
 */
public class SubscriberMethodFinder {

    private static final int MODIFIERS_IGNORE = Modifier.ABSTRACT | Modifier.STATIC;

    private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

    /**
     * 查找方法
     *
     * @param subscriberClass
     * @return
     */
    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        subscriberMethods = findUsingReflection(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;
        }
    }

    private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {

        List<SubscriberMethod> subscriberMethods = new ArrayList<>();
        Class<?> clazz = subscriberClass;
        boolean skipSuperClasses = false;
        while (clazz != null) {
            Method[] methods;
            try {
                methods = subscriberClass.getDeclaredMethods();
            } catch (Throwable th) {
                methods = subscriberClass.getMethods();
                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];
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    } else if (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 (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");
                }
            }
            if (skipSuperClasses) {
                clazz = null;
            } else {
                clazz = clazz.getSuperclass();
                String clazzName = clazz.getName();
                /** Skip system classes, this just degrades performance. */
                if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName.startsWith("android.")) {
                    clazz = null;
                }
            }
        }
        return subscriberMethods;
    }
}

InvokeHelper.class

/**
 * 方法執(zhí)行幫助類
 * <p/>
 * Author: 溫利東 on 2017/3/26 11:29.
 * blog: http://www.reibang.com/u/99f514ea81b3
 * github: https://github.com/LidongWen
 */
final class InvokeHelper {
    private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
    private static InvokeHelper ourInstance;
    private HandlerPoster handlerPoster;

    public static InvokeHelper getDefault() {
        if (ourInstance == null) {
            synchronized (InvokeHelper.class) {
                if (ourInstance == null) {
                    ourInstance = new InvokeHelper();
                }
            }
        }
        return ourInstance;
    }

    private InvokeHelper() {
        handlerPoster = new HandlerPoster(Looper.getMainLooper());
    }

    public void post(final Subscription subscription, final Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                //直接執(zhí)行
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                    //直接執(zhí)行
                    invokeSubscriber(subscription, event);
                } else {
                    // 放在handler內(nèi)執(zhí)行
                    handlerPoster.post(new Runnable() {
                        @Override
                        public void run() {
                            invokeSubscriber(subscription, event);
                        }
                    });
                }
                break;
            case BACKGROUND:
                if (isMainThread) {
                    //放在后臺線程執(zhí)行
//                    getExecutorService().execute(new Runnable() {
//                        @Override
//                        public void run() {
//                            invokeSubscriber(subscription,event);
//                        }
//                    });
                } else {
                    //執(zhí)行
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC:
                //放在異步線程內(nèi)執(zhí)行
                getExecutorService().execute(new Runnable() {
                    @Override
                    public void run() {
                        invokeSubscriber(subscription, event);
                    }
                });
                break;
            default:
                //拋異常
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }

    private void invokeSubscriber(Subscription subscription, Object event) {
        try {
            subscription.subscriberMethod.method.invoke(subscription.subscriberMethod.method, event);
        } catch (InvocationTargetException e) {
//            throw new InvocationTargetException(subscriberMethod.subscriber,e.getCause(),event);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Unexpected exception", e);
        }
    }

    ExecutorService getExecutorService() {
        return DEFAULT_EXECUTOR_SERVICE;
    }

    class HandlerPoster extends Handler {


        HandlerPoster(Looper looper) {
            super(looper);
        }
    }
}

EventBus.class


/**
 * <p/>
 * Author: 溫利東 on 2017/3/26 10:44.
 * blog: http://www.reibang.com/u/99f514ea81b3
 * github: https://github.com/LidongWen
 */

public class EventBus {
    public static String TAG = "EventBus";

    private static EventBus ourInstance;

    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    private final Map<Object, List<Class<?>>> typesBySubscriber;
    //粘性
    private final Map<Class<?>, Object> stickyEvents;

    private final SubscriberMethodFinder subscriberMethodFinder;

    //每個線程內(nèi)的一個隊列
    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

    public static EventBus getDefault() {
        if (ourInstance == null) {
            synchronized (EventBus.class) {
                if (ourInstance == null) {
                    ourInstance = new EventBus();
                }
            }
        }
        return ourInstance;
    }

    private EventBus() {
        //初始化一些數(shù)據(jù)
        subscriptionsByEventType = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        typesBySubscriber = new HashMap<>();
        subscriberMethodFinder = new SubscriberMethodFinder();
    }

    public void register(Object subscriber) {
        //1.找到所有方法
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

        //2.保存訂閱  subscriber();
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

    /**
     * 保存訂閱方法
     *
     * @param subscriber
     */
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //1.保存數(shù)據(jù)  粗恢,  如果重復(fù) 拋異常
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        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);


        //2.執(zhí)行粘性事件
        if (subscriberMethod.sticky) {
            // 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);
                }
            }
        }
    }

    private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        if (stickyEvent != null) {
            // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
            // --> Strange corner case, which we don't take care of here.
            postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
        }
    }

    private void postToSubscription(Subscription newSubscription, Object stickyEvent, boolean b) {
        InvokeHelper.getDefault().post(newSubscription, stickyEvent, b);
    }

    public synchronized void unRegister(Object subscriber) {
        //去除訂閱
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            typesBySubscriber.remove(subscriber);
        } else {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }


    public void post(Object event) {

        //1.放入執(zhí)行隊列
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        eventQueue.add(event);

        if (!postingState.isPosting) {
            postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        subscriptionFound |= postSingleEventForEventType(event, postingState, eventClass);
        if (!subscriptionFound) {
        }
    }

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    postToSubscription(subscription, event, postingState.isMainThread);
                    aborted = postingState.canceled;
                } finally {
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        return false;
    }

    public void postSticky(Object event) {
        //加入粘性緩存 stickyEvents
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        //執(zhí)行
        post(event);
    }

    public void cancelEventDelivery(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        if (!postingState.isPosting) {
            throw new EventBusException(
                    "This method may only be called from inside event handling methods on the posting thread");
        } else if (event == null) {
            throw new EventBusException("Event may not be null");
        } else if (postingState.event != event) {
            throw new EventBusException("Only the currently handled event may be aborted");
        } else if (postingState.subscription.subscriberMethod.threadMode != ThreadMode.POSTING) {
            throw new EventBusException(" event handlers may only abort the incoming event");
        }

        postingState.canceled = true;
    }

    /**
     * Gets the most recent sticky event for the given type.
     *
     * @see #postSticky(Object)
     */
    public <T> T getStickyEvent(Class<T> eventType) {
        synchronized (stickyEvents) {
            return eventType.cast(stickyEvents.get(eventType));
        }
    }

    /**
     * Remove and gets the recent sticky event for the given event type.
     *
     * @see #postSticky(Object)
     */
    public <T> T removeStickyEvent(Class<T> eventType) {
        synchronized (stickyEvents) {
            return eventType.cast(stickyEvents.remove(eventType));
        }
    }

    /**
     * Removes the sticky event if it equals to the given event.
     *
     * @return true if the events matched and the sticky event was removed.
     */
    public boolean removeStickyEvent(Object event) {
        synchronized (stickyEvents) {
            Class<?> eventType = event.getClass();
            Object existingEvent = stickyEvents.get(eventType);
            if (event.equals(existingEvent)) {
                stickyEvents.remove(eventType);
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * Removes all sticky events.
     */
    public void removeAllStickyEvents() {
        synchronized (stickyEvents) {
            stickyEvents.clear();
        }
    }

    final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<Object>();
        boolean isPosting;
        boolean isMainThread;
        Subscription subscription;
        Object event;
        boolean canceled;
    }

}

這邊我們就實現(xiàn)一個簡易版的EventBus了。

** 感受 **

不得不說,這套框架非常優(yōu)秀
并發(fā)性健壯性來講:用到了同步鎖儿奶,隊列設(shè)計,CopyOnWriteArrayList鳄抒,ConcurrentHashMap等用來保證線程安全 闯捎;
設(shè)計來講:非常巧妙,各種數(shù)據(jù)緩存,較少了數(shù)據(jù)檢索许溅。
整體架構(gòu)來講:牛瓤鼻!

** 自愧還差得遠呢。贤重。茬祷。o.O 還要加倍努力!2⒒取祭犯!**

github:https://github.com/LidongWen/EventBusWenld

希望我的文章不會誤導(dǎo)在觀看的你,如果有異議的地方歡迎討論和指正滚停。
如果能給觀看的你帶來收獲盹憎,那就是最好不過了。

人生得意須盡歡, 桃花塢里桃花庵
點個關(guān)注唄铐刘,對陪每,不信你點試試?
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末镰吵,一起剝皮案震驚了整個濱河市檩禾,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌疤祭,老刑警劉巖盼产,帶你破解...
    沈念sama閱讀 216,470評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異勺馆,居然都是意外死亡戏售,警方通過查閱死者的電腦和手機侨核,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來灌灾,“玉大人搓译,你說我怎么就攤上這事》嫦玻” “怎么了些己?”我有些...
    開封第一講書人閱讀 162,577評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長嘿般。 經(jīng)常有香客問我段标,道長,這世上最難降的妖魔是什么炉奴? 我笑而不...
    開封第一講書人閱讀 58,176評論 1 292
  • 正文 為了忘掉前任逼庞,我火速辦了婚禮,結(jié)果婚禮上瞻赶,老公的妹妹穿的比我還像新娘往堡。我一直安慰自己,他們只是感情好共耍,可當我...
    茶點故事閱讀 67,189評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著吨瞎,像睡著了一般痹兜。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上颤诀,一...
    開封第一講書人閱讀 51,155評論 1 299
  • 那天字旭,我揣著相機與錄音,去河邊找鬼崖叫。 笑死遗淳,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的心傀。 我是一名探鬼主播屈暗,決...
    沈念sama閱讀 40,041評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼脂男!你這毒婦竟也來了养叛?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,903評論 0 274
  • 序言:老撾萬榮一對情侶失蹤宰翅,失蹤者是張志新(化名)和其女友劉穎弃甥,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體汁讼,經(jīng)...
    沈念sama閱讀 45,319評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡淆攻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,539評論 2 332
  • 正文 我和宋清朗相戀三年阔墩,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瓶珊。...
    茶點故事閱讀 39,703評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡啸箫,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出艰毒,到底是詐尸還是另有隱情筐高,我是刑警寧澤,帶...
    沈念sama閱讀 35,417評論 5 343
  • 正文 年R本政府宣布丑瞧,位于F島的核電站柑土,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏绊汹。R本人自食惡果不足惜稽屏,卻給世界環(huán)境...
    茶點故事閱讀 41,013評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望西乖。 院中可真熱鬧狐榔,春花似錦、人聲如沸获雕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽届案。三九已至庵楷,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間楣颠,已是汗流浹背尽纽。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留童漩,地道東北人弄贿。 一個月前我還...
    沈念sama閱讀 47,711評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像矫膨,于是被迫代替她去往敵國和親差凹。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,601評論 2 353

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