首先是一个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 * @return */ public Observable toObserverable(Class 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 StudentEvent(String name) { 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", "小明"));
上面是这是发送事件;
private void initRxBus() { Subscription rxSbscription=RxBus.getInstance().toObserverable(StudentEvent.class) .subscribe(new Action1() { @Override public void call(StudentEvent studentEvent) { tv_rxbus.setText("id:"+ studentEvent.getId()+" name:"+ studentEvent.getName()); } }); }
这是接收事件。
现在写一下layout的布局
有一个button和一个textview,点击button 发送消息事件,这个发送的内容你可以自定义 StudentEvent的构造方法。在textview接受发来的事件或者数值就行了。