1、添加库的依赖,顺便把ButterKinfe添加一下,偷个懒哈哈
implementation 'com.jakewharton:butterknife:8.7.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'io.reactivex:rxjava:1.2.1'
2、新建RxBus类,不多说,这个自己从网上找一下
public class RxBus {
private static volatile RxBus defaultInstance;
private final Subject<Object, Object> bus;
public RxBus() {
bus = new SerializedSubject<>(PublishSubject.create());
}
// 单例RxBus
public static RxBus getDefault() {
if (defaultInstance == null) {
synchronized (RxBus.class) {
if (defaultInstance == null) {
defaultInstance = new RxBus();
}
}
}
return defaultInstance ;
}
// 发送一个新的事件
public void post (Object o) {
bus.onNext(o);
}
// 接受消息
public <T> Observable<T> toObservable (Class<T> eventType) {
return bus.ofType(eventType);
}
}
3、创建需要发送的事件类,我们要传一个city名字过去
public class CityEvent {
private String id;
private String cityName;
public CityEvent(String id, String cityName) {
this.id = id;
this.cityName = cityName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
}
4、发送事件,我们就设定在第二个activity的点击事件中了
RxBus.getDefault().post(new CityEvent("001","北京市"));
5、在MainActivity中接受事件
mSubscription = RxBus.getDefault().toObservable(CityEvent.class)
.subscribe(new Action1<CityEvent>() {
@Override
public void call(CityEvent cityEvent) {
text1.setText("添加城市成功,收到了ActivityTwo传来的城市名称"+ cityEvent.getCityName());
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
}
});
6、最后不要忘了取消订阅哦,防止内存泄漏
@Override
protected void onDestroy() {
if (!mSubscription.isUnsubscribed()){
mSubscription.unsubscribe();
}
super.onDestroy();
}
看看结果
总结
RxBus的简单用法,方便同学们查询
小Demo地址https://github.com/pengboboer/RxBusTest