站在巨人(RxJava)的肩膀上封装了一个简单的 EventBus。 很轻很小,使用也很简单。

单例模式;
按 tag: String 索引;
发送/接受 ? extends java.lang.Object;
支持在 IO 线程或 UI 线程中执行观察者回调;

上代码:RxBus.java

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
68
69
70
71
72
73
74
75
76
77
/**
* Created by jk.yeo on 16/3/1 17:47.
* 基于 RxJava 简单的 EventBus
*/
public class RxBus {
private static volatile RxBus mDefaultInstance;
private RxBus() {
}
public static RxBus getDefault() {
if (mDefaultInstance == null) {
synchronized (RxBus.class) {
if (mDefaultInstance == null) {
mDefaultInstance = new RxBus();
}
}
}
return mDefaultInstance;
}
PublishSubject<EventObject> publishSubject = PublishSubject.create();
private final Subject<EventObject, EventObject> _bus = new SerializedSubject<>(publishSubject);
public void send(String tag, Object object) {
EventObject eventObject = new EventObject(tag, object);
_bus.onNext(eventObject);
}
public interface ReceiveOnUiThread {
void OnReceive(String tag, Object object);
}
public interface ReceiveOnIOThread {
void OnReceive(String tag, Object object);
}
public void registerOnUiThread(final ReceiveOnUiThread receiveOnUiThread) {
_bus.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<EventObject>() {
@Override
public void call(EventObject eventObject) {
receiveOnUiThread.OnReceive(eventObject.getTag(), eventObject.getObject());
}
});
}
public void registerOnIOThread(final ReceiveOnIOThread receiveOnIOThread) {
_bus.observeOn(Schedulers.io())
.subscribe(new Action1<EventObject>() {
@Override
public void call(EventObject eventObject) {
receiveOnIOThread.OnReceive(eventObject.getTag(), eventObject.getObject());
}
});
}
private static class EventObject extends Object {
private String tag;
private Object object;
public EventObject(String tag, Object object) {
this.tag = tag;
this.object = object;
}
public String getTag() {
return tag;
}
public Object getObject() {
return object;
}
}
}

使用也很简单:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
RxBus.getDefault().registerOnIOThread(new RxBus.ReceiveOnIOThread() {
@Override
public void OnReceive(String tag, Object object) {
if (tag.equals("1"))
// do something on IO thread.
}
});
RxBus.getDefault().registerOnUiThread(new RxBus.ReceiveOnUiThread() {
@Override
public void OnReceive(String tag, Object object) {
if (tag.equals("2"))
// do something on Ui thread
}
});
RxBus.getDefault().send("1", "tag = 1");
RxBus.getDefault().send("2", UserModel.getInstance());

参考:RxBus—通过RxJava来替换EventBus