LiveData是17年GoogleIO大會上提出來的一個新技術。相對於通信總線類型的框架EventBus和RxBus來說,它更簡單,更簡潔、更解耦。
LiveEventBus是一款Android消息總線,基於LiveData,具有生命周期感知能力,支持Sticky,支持AndroidX,支持跨進程,支持跨APP
LiveDataBus優點
LiveDataBus的實現及其簡單
相對EventBus復雜的實現,LiveDataBus只需要一個類就可以實現
LiveDataBus可以減小APK包的大小
LiveDataBus只依賴Android官方組件LiveData,本身實現只一個類。EventBus 57Kb、RxJava 2.2M
LiveDataBus 依賴方支持更好
LiveDataBus只依賴Android官方組件LiveData,相比RxBus依賴的RxJava和RxAndroid,依賴方支持更好
LiveDataBus具有生命周期感知
LiveDataBus具有生命周期感知,在Android系統中使用調用者不需要調用反注冊,相比EventBus和RxBus使用更為方便,並且沒有內存泄漏風險。
LiveEventBus的特點
生命周期感知,消息隨時訂閱,自動取消訂閱
支持Sticky粘性消息
支持AndroidX
支持跨進程通信
支持跨APP通信
支持設置LifecycleObserver(如Activity)接收消息的模式:
1.整個生命周期(從onCreate到onDestroy)都可以實時收到消息
2.激活狀態(Started)可以實時收到消息,非激活狀態(Stoped)無法實時收到消息,需等到Activity重新變成激活狀態,方可收到消息
在工程中引用
implementation 'com.jeremyliao:live-event-bus:1.4.2'
配置
在 Application.onCreate 方法中配置:
LiveEventBus.get() .config() .supportBroadcast(this) .lifecycleObserverAlwaysActive(true);
具有生命周期感知能力,LifecycleOwner銷毀時自動取消訂閱,不需要調用removeObserver
保證 with() 中的key值相同,(注冊/接收)和發起通信
注冊:
LiveEventBus.get().with("LiveDataBusDemo1",String.class).observe(this, new Observer<String>() { @Override public void onChanged(@Nullable String s) { Log.i("aaa",s); } });
發起通信
LiveEventBus.get().with("LiveDataBusDemo1").post("LiveDataBus1");
以Forever模式訂閱和取消訂閱消息,Forever模式訂閱消息,需要手動調用removeObserver取消訂閱
注冊
private Observer<String> observer = new Observer<String>() { @Override public void onChanged(@Nullable String s) { Log.i("aaa",s); textView.setText("observeForever注冊的觀察者收到消息: " + s); } }; LiveEventBus.get() .with("LiveDataBusDemo2", String.class) .observeForever(observer);
發起通信
LiveEventBus.get().with("LiveDataBusDemo2").post("LiveDataBus2");
手動取消訂閱消息
LiveEventBus.get() .with("LiveDataBusDemo2", String.class) .removeObserver(observer);
Sticky模式(可以接收 前面/未注冊之前 發起通信的信息)
支持在訂閱消息的時候設置Sticky模式,這樣訂閱者可以接收到之前發送的消息,當然也支持后面發送的信息
以Sticky模式訂閱消息,具有生命周期感知能力,LifecycleOwner銷毀時自動取消訂閱,不需要調用removeObserver
注冊
LiveEventBus.get() .with("LiveDataBusDemo3", String.class) .observeSticky(this, new Observer<String>() { @Override public void onChanged(@Nullable String s) { Log.i("aaa",s); textView.setText("observeSticky注冊的觀察者收到消息: " + s); } });
發起通信(你可以在注冊之前和注冊之后分辨發起通知看效果)
LiveEventBus.get().with("LiveDataBusDemo3").post("LiveDataBus3");
observeStickyForever,Forever模式訂閱消息,需要手動調用removeObserver取消訂閱,和上面的一樣
注冊
private Observer<String> observer = new Observer<String>() { @Override public void onChanged(@Nullable String s) { Log.i("aaa",s); textView.setText("observeStickyForever注冊的觀察者收到消息: " + s); } }; LiveEventBus.get() .with("LiveDataBusDemo4", String.class) .observeStickyForever(observer);
發起通信
LiveEventBus.get().with("LiveDataBusDemo4").post("LiveDataBus4");
手動取消訂閱消息
LiveEventBus.get() .with("LiveDataBusDemo4", String.class) .removeObserver(observer);
混淆規則
-dontwarn com.jeremyliao.liveeventbus.** -keep class com.jeremyliao.liveeventbus.** { *; } -keep class android.arch.lifecycle.** { *; } -keep class android.arch.core.** { *; }
參考文檔:
https://github.com/JeremyLiao/LiveEventBus