面試官問我:Android EventBus的源碼,看我如何用漫畫裝逼!

一名優秀的Android開發,需要一份完備的 知識體系,在這裏,讓我們一起成長爲自己所想的那樣~。

基本使用步驟

1)定義事件Event

public class MyEvent {
    public MyEvent(String id, String message) {
        this.id = id;
        this.message = message;
    }

    public String id;

    public String message;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

2)註冊訂閱者,並實現回調方法

public class MainActivity extends Activity {

    private TextView message, next;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
    }

    /**
     * 初始化佈局組件
     */
    private void initView() {
        message = findViewById(R.id.message);
        next = findViewById(R.id.next);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMyEvent(MyEvent event) {
        message.setText(event.getMessage());
    }

    /**
     * 初始化數據
     */
    private void initData() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

通過EventBus.getDefault().register(this);方法註冊訂閱者。
3)發送消息

public class SecondActivity extends Activity {

    private TextView message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        initView();
    }

    /**
     * 初始化佈局組件
     */
    private void initView() {
        message = findViewById(R.id.message);
        message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new MyEvent("1","這是從SecondActivity發送過來的消息"));
                Toast.makeText(SecondActivity.this, "消息發送成功", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

通過EventBus.getDefault().post(new MyEvent(“1”,“這是從SecondActivity發送過來的消息”));方法發送消息

源碼分析

EventBus的使用先註冊訂閱者,並實現方法,然後再發送post消息,所以我們分析源碼也按照這個順序來。
1)實例化EventBus

EventBus.getDefault().register(this);

該方法首先獲取EventBus實例,然後再註冊,源碼如下所示:

  /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

可以看到,實例化EventBus是個雙重鎖的單例模式。

接下來看EventBus的構造函數,源碼如下:

 EventBus(EventBusBuilder builder) {
        logger = builder.getLogger();
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        mainThreadSupport = builder.getMainThreadSupport();
        mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        throwSubscriberException = builder.throwSubscriberException;
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;
    }

可以看到,在EventBus的構造函數中,初始化了一大堆變量,這邊主要關注前面兩個。

subscriptionsByEventType = new HashMap<>();:key:事件類型(如:MyEvent ),value:新的訂閱對象的集合,包括訂閱者和訂閱者包含的方法。具體賦值邏輯在後面會講,這邊先了解即可。
typesBySubscriber = new HashMap<>();:key:事件的訂閱者(MainActivity ),value:事件類型的集合。訂閱者跟事件類型是一對多的關係,所以一個界面可以支持多個事件類型。

2)註冊

 /**
     * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
     * are no longer interested in receiving events.
     * <p/>
     * Subscribers have event handling methods that must be annotated by {@link Subscribe}.
     * The {@link Subscribe} annotation also allows configuration like {@link
     * ThreadMode} and priority.
     */
    public void register(Object subscriber) {
        //1.拿到訂閱對象的類型;
        Class<?> subscriberClass = subscriber.getClass();
        //2.通過findSubscriberMethods方法獲取該訂閱者中的所有訂閱方法,因爲可能包含多個訂閱方法,所以返回集合。
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
               //3.通過subscribe方法爲每個訂閱方法進行訂閱。 
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

如何獲取該訂閱者中的所有訂閱方法,這邊主要看第二件事情的處理過程,及findSubscriberMethods方法的源碼

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //先拿訂閱對象在本地緩存中查找,提高性能。
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
		//默認情況下ignoreGeneratedIndex值是false的
        if (ignoreGeneratedIndex) {
           //使用反射方法拿到訂閱者中的訂閱方法  
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            //使用編譯期間生成的SubscriberInfo
            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;
        }
    }

可以看到上面方法做了三件事:
1.先拿訂閱對象在本地緩存中查找訂閱方法
2.如果本地獲取不到,則根據ignoreGeneratedIndex的值決定獲取訂閱方法的方式
3.本地保存訂閱方法。
可以看到獲取訂閱的關鍵方法爲:findUsingInfo(),那麼趕緊看下他的源碼,如下:

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            // 獲取訂閱者信息,沒有配置MyEventBusIndex返回null
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {
                SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                for (SubscriberMethod subscriberMethod : array) {
                    if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                        findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
                // 通過反射來查找訂閱方法,所以爲了提高性能,我們還是要用索引的形式使用EventBus
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

獲取到訂閱方法後,我們看真正的註冊方法subscribe(subscriber, subscriberMethod);

    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //獲取到事件類型(如:MyEvent )
        Class<?> eventType = subscriberMethod.eventType;
        //把訂閱者和訂閱者方法重新封裝成新的對象
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //事件類型爲key,新的訂閱者對象列表爲value,存儲進subscriptionsByEventType
        //該集合很重要,當post消息的時候,就是從該集合中查找訂閱者對象列表
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            //如果訂閱者對象列表爲空,則初始化出來,並加到subscriptionsByEventType中
            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;
            }
        }
		//訂閱者爲key,事件類型列表爲value,存儲進typesBySubscriber
        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);
            }
        }
    }

可以看到上面方法做了兩件事:
1.根據訂閱方法的優先級,添加到訂閱列表,事件類型爲key,訂閱列表爲value,存儲進subscriptionsByEventType
2.訂閱者爲key,事件類型列表爲value,存儲進typesBySubscriber

3)發送消息

    /** Posts the given event to the event bus. */
    public void post(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        //將當前要發送的事件加入到隊列中
        eventQueue.add(event);

        if (!postingState.isPosting) {
            postingState.isMainThread = isMainThread();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                 //循環從列表中拿event
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

循環從eventQueue取event,調用postSingleEvent方法:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
            //查找event事件和event子類事件
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

遍歷每個event事件或者子類,會再調用postSingleEventForEventType:

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
        	//subscriptionsByEventType有沒有很眼熟,在subscribe方法中,事件類型爲key,新的訂閱者對象列表爲value,存儲進subscriptionsByEventType
        	//獲取到新的訂閱對象列表
            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;
    }

可以看到,該方法其實就是從subscriptionsByEventType集合中,查找該event對應的訂閱者對象列表,然後遍歷訂閱者對象,調用postToSubscription方法。

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                	//通過反射,調用訂閱者的方法
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case MAIN_ORDERED:
                if (mainThreadPoster != null) {
                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    // temporary: technically not correct as poster not decoupled from subscriber
                    invokeSubscriber(subscription, event);
                }
                break;
            case BACKGROUND:
                if (isMainThread) {
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC:
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }

最後通過反射調用訂閱者的方法。
通過上面的分析可以看到發送消息其實是三重循環:
1.循環從eventQueue取event,調用postSingleEvent方法
2.遍歷每個event事件或者子類,調用postSingleEventForEventType方法
3.遍歷訂閱者對象,調用postToSubscription方法。
這種方式的算法複雜度還是很高的,event事件不做繼承可以提高發送流程的性能。

4)解綁

 /** Unregisters the given subscriber from all event classes. */
    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 {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

可以看到,先從typesBySubscriber集合中根據訂閱者獲取到事件類型列表subscribedTypes,然後循環事件類型,找出該事件類型對應的Subscriptions訂閱列表,循環遍歷,當Subscription對象中包含該訂閱者subscriber對象時,把該Subscription對象從訂閱列表中刪除,再從從typesBySubscriber中刪除對應的訂閱者。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章