android跨进程订阅消息,Android 消息总线 LiveEventBus

## 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值