本文由雲+社區發表java
事件總線核心邏輯的實現。git
Android中存在各類通訊場景,如Activity
之間的跳轉,Activity
與Fragment
以及其餘組件之間的交互,以及在某個耗時操做(如請求網絡)以後的callback回調等,互相之之間每每須要持有對方的引用,每一個場景的寫法也有差別,致使耦合性較高且不便維護。以Activity
和Fragment
的通訊爲例,官方作法是實現一個接口,而後持有對方的引用,再強行轉成接口類型,致使耦合度偏高。再以Activity
的返回爲例,一方須要設置setResult
,而另外一方須要在onActivityResult
作對應處理,若是有多個返回路徑,代碼就會十分臃腫。而SimpleEventBus
(本文最終實現的簡化版事件總線)的寫法以下:github
public class MainActivity extends AppCompatActivity { TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.tv_demo); mTextView.setText("MainActivity"); mTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }); EventBus.getDefault().register(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void onReturn(Message message) { mTextView.setText(message.mContent); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
來源Activity
:編程
public class SecondActivity extends AppCompatActivity { TextView mTextView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.tv_demo); mTextView.setText("SecondActivity,點擊返回"); mTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Message message = new Message(); message.mContent = "從SecondActivity返回"; EventBus.getDefault().post(message); finish(); } }); } }
效果以下:vim
彷佛只是換了一種寫法,但在場景越發複雜後,EventBus
可以體現出更好的解耦能力。設計模式
主要涉及三方面的知識:網絡
觀察者模式(or 發佈-訂閱模式)併發
Android消息機制ide
Java併發編程oop
本文能夠認爲是greenrobot/EventBus這個開源庫的源碼閱讀指南,筆者在看設計模式相關書籍的時候瞭解到這個庫,以爲有必要實現一下核心功能以加深理解。
EventBus
的使用分三個步驟:註冊監聽、發送事件和取消監聽,相應本文也將分這三步來實現。
定義一個註解:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Subscribe { ThreadMode threadMode() default ThreadMode.POST; }
greenrobot/EventBus
還支持優先級和粘性事件,這裏只支持最基本的能力:區分線程,由於如更新UI的操做必須放在主線程。ThreadMode
以下:
public enum ThreadMode { MAIN, // 主線程 POST, // 發送消息的線程 ASYNC // 新開一個線程發送 }
在對象初始化的時候,使用register
方法註冊,該方法會解析被註冊對象的全部方法,並解析聲明瞭註解的方法(即觀察者),核心代碼以下:
public class EventBus { ... public void register(Object subscriber) { if (subscriber == null) { return; } synchronized (this) { subscribe(subscriber); } } ... private void subscribe(Object subscriber) { if (subscriber == null) { return; } // TODO 巨踏馬難看的縮進 Class<?> clazz = subscriber.getClass(); while (clazz != null && !isSystemClass(clazz.getName())) { final Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { Subscribe annotation = method.getAnnotation(Subscribe.class); if (annotation != null) { Class<?>[] paramClassArray = method.getParameterTypes(); if (paramClassArray != null && paramClassArray.length == 1) { Class<?> paramType = convertType(paramClassArray[0]); EventType eventType = new EventType(paramType); SubscriberMethod subscriberMethod = new SubscriberMethod(method, annotation.threadMode(), paramType); realSubscribe(subscriber, subscriberMethod, eventType); } } } clazz = clazz.getSuperclass(); } } ... private void realSubscribe(Object subscriber, SubscriberMethod method, EventType eventType) { CopyOnWriteArrayList<Subscription> subscriptions = mSubscriptionsByEventtype.get(subscriber); if (subscriptions == null) { subscriptions = new CopyOnWriteArrayList<>(); } Subscription subscription = new Subscription(subscriber, method); if (subscriptions.contains(subscription)) { return; } subscriptions.add(subscription); mSubscriptionsByEventtype.put(eventType, subscriptions); } ... }
執行過這些邏輯後,該對象全部的觀察者方法都會被存在一個Map中,其Key是EventType
,即觀察事件的類型,Value是訂閱了該類型事件的全部方法(即觀察者)的一個列表,每一個方法和對象一塊兒封裝成了一個Subscription
類:
public class Subscription { public final Reference<Object> subscriber; public final SubscriberMethod subscriberMethod; public Subscription(Object subscriber, SubscriberMethod subscriberMethod) { this.subscriber = new WeakReference<>(subscriber);// EventBus3 沒用弱引用? this.subscriberMethod = subscriberMethod; } @Override public int hashCode() { return subscriber.hashCode() + subscriberMethod.methodString.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof Subscription) { Subscription other = (Subscription) obj; return subscriber == other.subscribe && subscriberMethod.equals(other.subscriberMethod); } else { return false; } } }
如此,即是註冊監聽方法的核心邏輯了。
消息的發送代碼很簡單:
public class EventBus { ... private EventDispatcher mEventDispatcher = new EventDispatcher(); private ThreadLocal<Queue<EventType>> mThreadLocalEvents = new ThreadLocal<Queue<EventType>>() { @Override protected Queue<EventType> initialValue() { return new ConcurrentLinkedQueue<>(); } }; ... public void post(Object message) { if (message == null) { return; } mThreadLocalEvents.get().offer(new EventType(message.getClass())); mEventDispatcher.dispatchEvents(message); } ... }
比較複雜一點的是須要根據註解聲明的線程模式在對應的線程進行發佈:
public class EventBus { ... private class EventDispatcher { private IEventHandler mMainEventHandler = new MainEventHandler(); private IEventHandler mPostEventHandler = new DefaultEventHandler(); private IEventHandler mAsyncEventHandler = new AsyncEventHandler(); void dispatchEvents(Object message) { Queue<EventType> eventQueue = mThreadLocalEvents.get(); while (eventQueue.size() > 0) { handleEvent(eventQueue.poll(), message); } } private void handleEvent(EventType eventType, Object message) { List<Subscription> subscriptions = mSubscriptionsByEventtype.get(eventType); if (subscriptions == null) { return; } for (Subscription subscription : subscriptions) { IEventHandler eventHandler = getEventHandler(subscription.subscriberMethod.threadMode); eventHandler.handleEvent(subscription, message); } } private IEventHandler getEventHandler(ThreadMode mode) { if (mode == ThreadMode.ASYNC) { return mAsyncEventHandler; } if (mode == ThreadMode.POST) { return mPostEventHandler; } return mMainEventHandler; } }// end of the class ... }
三種線程模式分別以下,DefaultEventHandler
(在發佈線程執行觀察者放方法):
public class DefaultEventHandler implements IEventHandler { @Override public void handleEvent(Subscription subscription, Object message) { if (subscription == null || subscription.subscriber.get() == null) { return; } try { subscription.subscriberMethod.method.invoke(subscription.subscriber.get(), message); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } }
MainEventHandler
(在主線程執行):
public class MainEventHandler implements IEventHandler { private Handler mMainHandler = new Handler(Looper.getMainLooper()); DefaultEventHandler hanlder = new DefaultEventHandler(); @Override public void handleEvent(final Subscription subscription, final Object message) { mMainHandler.post(new Runnable() { @Override public void run() { hanlder.handleEvent(subscription, message); } }); } }
AsyncEventHandler
(新開一個線程執行):
public class AsyncEventHandler implements IEventHandler { private DispatcherThread mDispatcherThread; private IEventHandler mEventHandler = new DefaultEventHandler(); public AsyncEventHandler() { mDispatcherThread = new DispatcherThread(AsyncEventHandler.class.getSimpleName()); mDispatcherThread.start(); } @Override public void handleEvent(final Subscription subscription, final Object message) { mDispatcherThread.post(new Runnable() { @Override public void run() { mEventHandler.handleEvent(subscription, message); } }); } private class DispatcherThread extends HandlerThread { // 關聯了AsyncExecutor消息隊列的Handle Handler mAsyncHandler; DispatcherThread(String name) { super(name); } public void post(Runnable runnable) { if (mAsyncHandler == null) { throw new NullPointerException("mAsyncHandler == null, please call start() first."); } mAsyncHandler.post(runnable); } @Override public synchronized void start() { super.start(); mAsyncHandler = new Handler(this.getLooper()); } } }
以上即是發佈消息的代碼。
最後一個對象被銷燬還要註銷監聽,不然容易致使內存泄露,目前SimpleEventBus
用的是WeakReference
,可以經過GC自動回收,但不知道greenrobot/EventBus
爲何沒這樣實現,待研究。註銷監聽其實就是遍歷Map,拿掉該對象的訂閱便可:
public class EventBus { ... public void unregister(Object subscriber) { if (subscriber == null) { return; } Iterator<CopyOnWriteArrayList<Subscription>> iterator = mSubscriptionsByEventtype.values().iterator(); while (iterator.hasNext()) { CopyOnWriteArrayList<Subscription> subscriptions = iterator.next(); if (subscriptions != null) { List<Subscription> foundSubscriptions = new LinkedList<>(); for (Subscription subscription : subscriptions) { Object cacheObject = subscription.subscriber.get(); if (cacheObject == null || cacheObject.equals(subscriber)) { foundSubscriptions.add(subscription); } } subscriptions.removeAll(foundSubscriptions); } // 若是針對某個Event的訂閱者數量爲空了,那麼須要從map中清除 if (subscriptions == null || subscriptions.size() == 0) { iterator.remove(); } } } ... }
以上即是事件總線最核心部分的代碼實現,完整代碼見vimerzhao/SimpleEventBus,後面發現問題更新或者進行升級也只會改動倉庫的代碼。
因爲時間關係,目前只研究了EventBus
的核心部分,還有幾個值得深刻研究的點,在此記錄一下,也歡迎路過的大牛指點一二。
實際使用時,註解和反射會致使性能問題,但EventBus3
已經經過Subscriber Index
基本解決了這一問題,實現也很是有意思,是經過註解處理器(Annotation Processor
)把耗時的邏輯從運行期提早到了編譯期,經過編譯期生成的索引來給運行期提速,這也是這個名字的由來。
若是訂閱者不少會不會影響體驗,畢竟原始的方法是點對點的消息傳遞,不會有這種問題,若是部分訂閱者還沒有初始化怎麼辦。等等。目前EventBus3
提供了優先級和粘性事件的屬性來進一步知足開發需求。可是否完全解決問題了還有待驗證。
EventBus
是進程內的消息管理機制,而且從開源社區的反饋來看這個項目是很是成功的,但稍微有點體量的APP都作了進程拆分,因此是否有必要支持多進程,可否在保證性能的狀況下提供同等的代碼解耦能力,也值得繼續挖掘。目前有lsxiao/Apollo和Xiaofei-it/HermesEventBus等可供參考。
《Android開發藝術探索》第十章
此文已由做者受權騰訊雲+社區發佈