如何在RxJava Android中订阅和事件

时间:2016-09-03 14:13:28

标签: android events rx-java publish-subscribe

我正在构建一个Android应用,并且是Rxjava的新手,有一个初学者的问题: 如何在活动开始时订阅活动,并在活动停止时关闭订阅?

我很困惑如何实现它。

1 个答案:

答案 0 :(得分:0)

您必须创建PublishSubject的实例并订阅它。当您想要发送和事件时,您需要调用onNext()实例的PublishSubject

注意:您必须为每种订阅类型保留一个实例。

首先,您必须创建EventSubscription类来保存特定的PublishSubject实例:

<强> EventSubscription.java:

public class EventSubscription {
    private static EventSubscription instance;

    private PublishSubject<String> subject = PublishSubject.create();

    /**
     * Singleton
     */
    public static EventSubscription getInstance() {
        if (instance == null) {
            instance = new EventSubscription();
        }
        return instance;
    }

    /**
     * Pass any event down to event listeners.
     */
    public void setString(String eventName) {
        subject.onNext(eventName);
    }

    /**
     * Subscribe to this Observable. On event
     */
    public Observable<String> getEvents() {
        return subject;
    }
}

在您的活动中,您还需要持有订阅实例,以便能够在活动停止时取消订阅。请参阅以下活动类:

public class MyActivity extends Activity {

    private Subscription mMySubscription;

    @Override
    public void onStart(){

        // Start the subscription
        mMySubscription = EventSubscription.getInstance().getEvents()
                .subscribe(new Action1<String>() {

                    @Override
                    public void call(String eventName){

                        // Handle new event
                    }
                });
    }

    @Override
    public void onStop(){

        if(mMySubscription != null && ! mMySubscription.isUnsubscribed()){

            // if your subscription already unsubscribed
            mMySubscription.unsubscribe();
        }
    }

}