Kiwiapps Ltd. Kiwiapps Ltd. - 3 months ago 6
Android Question

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?

I confused how to implement it.

Answer

You have to create an instance of PublishSubject and subscribe to it. and when you want to send and event you need to call onNext() of the PublishSubject instance.

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

}
Comments