RxBus并不是一个库,而是一种模式。相信大多数开发者都使用过EventBus,作为事件总线通信库,如果你的项目已经加入RxJava和EventBus,不妨用RxBus代替EventBus,以减少库的依赖。
一、添加RxJava和RxAndroid依赖
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
二、 新建RxBus类
public class RxBus {
private static volatile RxBus mInstance;
private final Subject bus;
public RxBus()
{
bus = new SerializedSubject<>(PublishSubject.create());
}
/**
* 单例模式RxBus
*
* @return
*/
public static RxBus getInstance()
{
RxBus rxBus2 = mInstance;
if (mInstance == null)
{
synchronized (RxBus.class)
{
rxBus2 = mInstance;
if (mInstance == null)
{
rxBus2 = new RxBus();
mInstance = rxBus2;
}
}
}
return rxBus2;
}
/**
* 发送消息
*
* @param object
*/
public void post(Object object)
{
bus.onNext(object);
}
/**
* 接收消息
*
* @param eventType
* @param <T>
* @return
*/
public <T> Observable<T> toObserverable(Class<T> eventType)
{
return bus.ofType(eventType);
}
}
三、创建你需要发送的事件类
public class StudentEvent {
private String id;
private String name;
public StudentEvent(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
四、发送事件
RxBus.getInstance().post(new StudentEvent("007","小明"));
五、接收事件
rxSbscription=RxBus.getInstance().toObserverable(StudentEvent.class)
.subscribe(new Action1<StudentEvent>() {
@Override
public void call(StudentEvent studentEvent) {
textView.setText("id:"+ studentEvent.getId()+" name:"+ studentEvent.getName());
}
});
六、取消订阅
@Override
protected void onDestroy() {
if (!rxSbscription.isUnsubscribed()){
rxSbscription.unsubscribe();
}
super.onDestroy();
}
七、MainActivity整体代码
public class MainActivity extends AppCompatActivity {
TextView textView;
Subscription rxSbscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.button);
//接收事件
rxBusObservers();
//监听跳转
rxBusPost();
}
//监听跳转
private void rxBusPost() {
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送事件
RxBus.getInstance().post(new StudentEvent("007", "小明"));
}
});
}
//接收事件
private void rxBusObservers() {
//rxSbscription是Sbscription的对象,
// 我们这里把RxBus.getInstance().toObserverable(StudentEvent.class)赋值给rxSbscription以方便生命周期结束时取消订阅事件
rxSbscription = RxBus.getInstance().toObserverable(StudentEvent.class)
.subscribe(new Action1<StudentEvent>() {
@Override
public void call(StudentEvent studentEvent) {
textView.setText("id:" + studentEvent.getId() + " name:" + studentEvent.getName());
}
});
}
@Override
protected void onDestroy() {
if (!rxSbscription.isUnsubscribed()) {
rxSbscription.unsubscribe();
}
super.onDestroy();
}
}