RxBus

相信大多数开发者都使用过EventBus或者Otto(我还未实践过),作为事件总线通信库,如果你的项目已经加入RxJava和EventBus(或Otto),那不妨用RxBus代替EventBus或者Otto,省去更多库的依赖。

RxJava

之前已经分享过RxJava知识,可以点击RxJava,这里不再细说。

RxBus

假设你已经对RxJava有所了解,再继续往下看。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class RxBus {
private static RxBus mRxBus = null;
/**
* PublishSubject只会把在订阅发生的时间点之后来自原始Observable的数据发射给观察者
*/
private Subject<Object, Object> mRxBusObserverable = new SerializedSubject<>(PublishSubject.create());
public static synchronized RxBus getInstance() {
if (mRxBus == null) {
mRxBus = new RxBus();
}
return mRxBus;
}
public void post(Object o) {
if (hasObservers()) {
mRxBusObserverable.onNext(o);
}
}
public Observable<Object> toObserverable() {
return mRxBusObserverable;
}
/**
* 判断是否有订阅者
*/
public boolean hasObservers() {
return mRxBusObserverable.hasObservers();
}
}

代码调用

先模拟一个订阅者,用hasObservers判断是否有订阅者,然后再发送。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class RxBusActivity extends AppCompatActivity {
private CompositeSubscription mCompositeSubscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rx_bus);
rxBusObservers();
rxBusPost();
}
private void rxBusPost() {
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RxBus.getInstance().post(HandleEvent.getInstance());
}
});
}
public void addSubscription(Subscription subscription) {
if (this.mCompositeSubscription == null) {
this.mCompositeSubscription = new CompositeSubscription();
}
this.mCompositeSubscription.add(subscription);
}
private void rxBusObservers() {
Subscription subscription = RxBus.getInstance()
.toObserverable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Object>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Object event) {
if (event instanceof HandleEvent) {
//do something
Log.d("wxl", "rxBusHandle");
}
}
});
addSubscription(subscription);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("wxl", "onDestroy");
if (this.mCompositeSubscription != null) {
//取消注册,以避免内存泄露
this.mCompositeSubscription.unsubscribe();
}
}
}

完整代码

https://github.com/WuXiaolong/AndroidSamples

EventBus源码解析

附上大牛们分析的EventBus源码,有兴趣可以看看
EventBus源码研读 by kymjs张涛
EventBus 源码解析 by Trinea

附录

RxJava-Android-Samples



联系作者

我的微信公众号:吴小龙同学,欢迎关注交流,公号回复关键字「1024」有惊喜哦。