简体   繁体   English

如何在RxJava Android中订阅和事件

[英]How to subscribe to and event in RxJava Android

I'm building an Android app, and new to Rxjava, having a beginner's question: How can i subscribe to an event on activity starts, and close the subscription on activity stops? 我正在构建一个Android应用程序,并且是Rxjava的新手,所以有一个初学者的问题:如何在活动开始时订阅事件,并在活动停止时关闭订阅?

I confused how to implement it. 我很困惑如何实现它。

You have to create an instance of PublishSubject and subscribe to it. 您必须创建PublishSubject的实例并进行订阅。 and when you want to send and event you need to call onNext() of the PublishSubject instance. 当您要发送事件时,您需要调用PublishSubject实例的onNext()

Note: you have to hold one instance for each type of subscriptions. 注意:每种类型的订阅必须拥有一个实例。

First of all you must create EventSubscription class to hold specific PublishSubject instance: 首先,您必须创建EventSubscription类来保存特定的PublishSubject实例:

EventSubscription.java: 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;
    }
}

And in your activity you also need to hold a subscription instance to be able to unsubscribe it on activity stop. 并且在您的活动中,您还需要保留一个订阅实例,以便能够在活动停止时取消订阅该实例。 see the following activity class: 请参阅以下活动类:

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();
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM