## LiveEventBus
LiveEventBus是一款Android消息总线,基于LiveData,具有生命周期感知能力,支持Sticky,支持AndroidX,支持跨进程,支持跨APP
- 生命周期感知,消息随时订阅,自动取消订阅
- 支持Sticky粘性消息
- 支持AndroidX
- 支持跨进程通信
- 支持跨APP通信
- 支持设置LifecycleObserver(如Activity)接收消息的模式:
### 安装及配置
```
// build.gradle
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
// Live Event Bus for Data Transfer
implementation 'com.jeremyliao:live-event-bus:1.5.7'
}
```
### 初始化
```java
public class MyApplication extends Application {
private static MyApplication application;
@Override
public void onCreate() {
super.onCreate();
application = this;
// 初始化数据总线
LiveEventBus.config()
.lifecycleObserverAlwaysActive(false)
.enableLogger(false); // default=false
}
public static MyApplication getApplication() {
return application;
}
}
```
### 使用
```java
// 普通订阅,无需手动移除
LiveEventBus
.get("key_name", String.class)
.observe(this, new Observer() {
@Override
public void onChanged(@Nullable String s) {
}
});
// Forever模式,需要手动移除
LiveEventBus
.get("key_name", String.class)
.observeForever(observer);
// 移除 observer
LiveEventBus
.get("key_name", String.class)
.removeObserver(observer);
// 发送消息
LiveEventBus
.get("key_name")
.post(value);
// 延迟发送
LiveEventBus
.get("key_name")
.postDelay(value, 1000);
// 跨进程 跨APP 发送
LiveEventBus
.get("key_name")
.broadcast(value);
// Sticky 模式,订阅后可接收到之前的内容
LiveEventBus
.get("sticky_key", String.class)
.observeSticky(this, new Observer() {
@Override
public void onChanged(@Nullable String s){
}
});
// Sticky模式 Forever
LiveEventBus
.get("sticky_key", String.class)
.observeStickyForever(observer);
```
### 参考博客
1. https://github.com/JeremyLiao/LiveEventBus
1116

被折叠的 条评论
为什么被折叠?



