自己動手寫事件總線(EventBus)

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

本文由云+社區發表

事件總線核心邏輯的實現。

<!--more-->

EventBus的作用

Android中存在各種通信場景,如Activity之間的跳轉,ActivityFragment以及其他組件之間的交互,以及在某個耗時操作(如請求網絡)之后的callback回調等,互相之之間往往需要持有對方的引用,每個場景的寫法也有差異,導致耦合性較高且不便維護。以ActivityFragment的通信為例,官方做法是實現一個接口,然后持有對方的引用,再強行轉成接口類型,導致耦合度偏高。再以Activity的返回為例,一方需要設置setResult,而另一方需要在onActivityResult做對應處理,如果有多個返回路徑,代碼就會十分臃腫。而SimpleEventBus(本文最終實現的簡化版事件總線)的寫法如下:


public class MainActivity extends AppCompatActivity {TextView mTextView;@Overrideprotected 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() {@Overridepublic 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);}@Overrideprotected void onDestroy() {super.onDestroy();EventBus.getDefault().unregister(this);}}

來源Activity


public class SecondActivity extends AppCompatActivity {TextView mTextView;@Overrideprotected 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() {@Overridepublic void onClick(View view) {Message message = new Message();message.mContent = "從SecondActivity返回";EventBus.getDefault().post(message);finish();}});}}

效果如下:

似乎只是換了一種寫法,但在場景愈加復雜后,EventBus能夠體現出更好的解耦能力。

背景知識

主要涉及三方面的知識:

  1. 觀察者模式(or 發布-訂閱模式)

  2. Android消息機制

  3. Java并發編程

本文可以認為是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;}@Overridepublic int hashCode() {return subscriber.hashCode() + subscriberMethod.methodString.hashCode();}@Overridepublic 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>>() {@Overrideprotected 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 {@Overridepublic 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();@Overridepublic void handleEvent(final Subscription subscription, final Object message) {mMainHandler.post(new Runnable() {@Overridepublic 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();}@Overridepublic void handleEvent(final Subscription subscription, final Object message) {mDispatcherThread.post(new Runnable() {@Overridepublic void run() {mEventHandler.handleEvent(subscription, message);}});}private class DispatcherThread extends HandlerThread {// 關聯了AsyncExecutor消息隊列的HandleHandler 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);}@Overridepublic 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等可供參考。

參考

  • greenrobot/EventBus

  • hehonghui/AndroidEventBus

  • 《Android開發藝術探索》第十章

此文已由作者授權騰訊云+社區發布


轉載于:https://my.oschina.net/qcloudcommunity/blog/2995084

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388727.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388727.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388727.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

viz::viz3d報錯_我可以在Excel中獲得該Viz嗎?

viz::viz3d報錯Have you ever found yourself in the following situation?您是否遇到以下情況&#xff1f; Your team has been preparing and working tireless hours to create and showcase the end product — an interactive visual dashboard. It’s a culmination of…

php 數組合并字符,PHP將字符串或數組合并到一個數組內方法

本文主要和大家分享PHP將字符串或數組合并到一個數組內方法&#xff0c;有兩種方法&#xff0c;希望希望能幫助到大家。一般寫法&#xff1a;<?php /*** add a string or an array to another array** param array|string $val* param array $array*/function add_val_to_a…

xcode 4 最低的要求是 10.6.6的版本,如果你是 10.6.3的版本,又不想升級的話。可以考慮通過修改版本號的方法進行安裝

xcode 4 最低的要求是 10.6.6的版本&#xff0c;如果你是 10.6.3的版本&#xff0c;又不想升級的話。可以考慮通過修改版本號的方法進行安裝。 一、打開控制臺&#xff1b; 二、使用root用戶&#xff1b; 命令&#xff1a;sudo -s 之后輸入密碼即可 三、編輯 /System/Library/C…

android 調試技巧

1.查看當前堆棧 Call tree new Exception(“print trace”).printStackTrace(); &#xff08;在logcat中打印當前函數調用關系&#xff09; 2.MethodTracing 性能分析與優&#xff08; 函數占用CPU時間&#xff0c; 調用次數&#xff0c; 函數調用關系&#xff09; a) 在程序…

Xml序列化

xml序列化 實現思路 通過程序生成一個xml文件來備份手機短信. 先獲取手機短信的內容 —>通過xml備份.StringBuffer 代碼如下public void click(View view) {StringBuffer sb new StringBuffer();sb.append("<?xml version\"1.0\" encoding\"UTF-8\…

java 添加用戶 數據庫,跟屌絲學DB2 第二課 建立數據庫以及添加用戶

在安裝DB2 之后&#xff0c;就可以在 DB2 環境中創建自己的數據庫。首先考慮數據庫應該使用哪個實例。實例(instance) 提供一個由數據庫管理配置(DBM CFG)文件控制的邏輯層&#xff0c;可以在這里將多個數據庫分組在一起。DBM CFG 文件包含一組 DBM CFG 參數&#xff0c;可以使…

iphone視頻教程

公開課介紹 本課程共28集 翻譯至第15集 網易正在翻譯16-28集 敬請關注 返回公開課首頁 一鍵分享&#xff1a;  網易微博開心網豆瓣網新浪微博搜狐微博騰訊微博郵件 講師介紹 名稱&#xff1a;Alan Cannistraro 課程介紹 如果你對iPhone Development有興趣&#xff0c;以下是入…

在Python中有效使用JSON的4個技巧

Python has two data types that, together, form the perfect tool for working with JSON: dictionaries and lists. Lets explore how to:Python有兩種數據類型&#xff0c;它們一起構成了使用JSON的理想工具&#xff1a; 字典和列表 。 讓我們探索如何&#xff1a; load a…

Vlan中Trunk接口配置

Vlan中Trunk接口配置 參考文獻&#xff1a;HCNA網絡技術實驗指南 模擬器&#xff1a;eNSP 實驗環境&#xff1a; 實驗目的&#xff1a;掌握Trunk端口配置 掌握Trunk端口允許所有Vlan配置方法 掌握Trunk端口允許特定Vlan配置方法 實驗拓撲&#xff1a; 實驗IP地址 &#xff1a;…

django中的admin組件

Admin簡介&#xff1a; Admin:是django的后臺 管理的wed版本 我們現在models.py文件里面建幾張表&#xff1a; class Author(models.Model):nid models.AutoField(primary_keyTrue)namemodels.CharField( max_length32)agemodels.IntegerField()# 與AuthorDetail建立一對一的關…

虛擬主機創建虛擬lan_創建虛擬背景應用

虛擬主機創建虛擬lanThis is the Part 2 of the MediaPipe Series I am writing.這是我正在編寫的MediaPipe系列的第2部分。 Previously, we saw how to get started with MediaPipe and use it with your own tflite model. If you haven’t read it yet, check it out here.…

.net程序員安全注意代碼及服務器配置

概述 本人.net架構師&#xff0c;軟件行業為金融資訊以及股票交易類的軟件產品設計開發。由于長時間被黑客攻擊以及騷擾。從事高量客戶訪問的服務器解決架構設計以及程序員編寫指導工作。特此總結一些.net程序員在代碼編寫安全以及服務器設置安全常用到的知識。希望能給對大家…

文件的讀寫及其相關

將軟件布置在第三方電腦上會出現無法提前指定絕對路徑的情況&#xff0c;這回影響到后續的文件讀寫&#xff1b;json文件是數據交換的一種基本方法&#xff0c;為了減少重復造輪子&#xff0c;經行標準化代碼。關于路徑&#xff1a; import os workspaceos.getcwd() pathos.pat…

接口測試框架2

現在市面上做接口測試的工具很多&#xff0c;比如Postman&#xff0c;soapUI, JMeter, Python unittest等等&#xff0c;各種不同的測試工具擁有不同的特色。但市面上的接口測試工具都存在一個問題就是無法完全吻合的去適用沒一個項目&#xff0c;比如數據的處理&#xff0c;加…

python 傳不定量參數_Python中的定量金融

python 傳不定量參數The first quantitative class for vanilla finance and quantitative finance majors alike has to do with the time value of money. Essentially, it’s a semester-long course driving notions like $100 today is worth more than $100 a year from …

axis為amchart左右軸的參數

<axis>left</axis> <!-- [left] (left/ right) indicates which y axis should be used --> <title>流通股</title> <!-- [] (graph title) --> <…

雷軍宣布紅米 Redmi 品牌獨立,這對小米意味著什么?

雷鋒網消息&#xff0c;1 月 3 日&#xff0c;小米公司宣布&#xff0c;將在 1 月 10 日召開全新獨立品牌紅米 Redmi 發布會。從小米公布的海報來看&#xff0c;Redmi 品牌標識出現的倒影中&#xff0c;有 4800 的字樣&#xff0c;這很容易讓人聯想起此前小米總裁林斌所宣布的 …

JAVA的rotate怎么用,java如何利用rotate旋轉圖片_如何在Java中旋轉圖形

I have drawn some Graphics in a JPanel, like circles, rectangles, etc.But I want to draw some Graphics rotated a specific degree amount, like a rotated ellipse. What should I do?解決方案If you are using plain Graphics, cast to Graphics2D first:Graphics2D …

貝葉斯 樸素貝葉斯_手動執行貝葉斯分析

貝葉斯 樸素貝葉斯介紹 (Introduction) Bayesian analysis offers the possibility to get more insights from your data compared to the pure frequentist approach. In this post, I will walk you through a real life example of how a Bayesian analysis can be perform…

vs2005 vc++ 生成非托管的 不需要.net運行環境的exe程序方法

在VS2005里開發的VC程序在編譯的時候&#xff0c;微軟默認會加入自己的 .Net Framework &#xff08;方便推廣自家產品&#xff09;&#xff0c;讓你的VC程序依賴它&#xff0c;這就導致程序編譯后&#xff0c;無法跟往常一樣直接打包&#xff0c;在別的機器就能正常運行。如果…