1. 程式人生 > >RxBus的簡單用例,很好用那個

RxBus的簡單用例,很好用那個

首先是一個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 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<StudentEvent>() {
                @Override
public void call(StudentEvent studentEvent) {
                tv_rxbus.setText("id:"+ studentEvent.getId()+"  name:"+ studentEvent.getName());
}
            });
}

這是接收事件。

現在寫一下layout的佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.zhangjiqun.retrifit.MainActivity">
    <TextView
android:text="rxbus"
android:id="@+id/rxbus"
android:gravity="center"
android:layout_marginBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
    <Button
android:id="@+id/bt_rxbus"
android:text="rxbus_send"
android:layout_width="match_parent"
android:layout_height="wrap_content" /></LinearLayout>
有一個button和一個textview,點選button 傳送訊息事件,這個傳送的內容你可以自定義 StudentEvent的構造方法。在textview接受發來的事件或者數值就行了。