RxJava: convert a listener into an Observable

Reading time ~1 minute

In Java it’s common to work with listeners. And if you work with RxJava, you will prefer to use an Observable instead of listeners. But what if you have to deal with a library and you cannot change the source code?

There’s a simple way to create an Observable around a listener.

Suppose we have an interface

1
ValueUpdateListener
and an object
1
ValueUpdater
that will call our listener:

public interface ValueUpdateListener {
    
    void onValueChanged(@NonNull String value);

}

public class ValueUpdater {
    
    // in some point of the class...
    
    public void registerListener(ValueUpdateListener listener) {
        //...
    };
    
    public void unregisterListener(ValueUpdateListener listener) {
        //...
    };
}

We can create an Observable like this:

public Observable<String> observableListenerWrapper() {

    return Observable.create(new Observable.OnSubscribe<String>() {

        @Override
        public void call(Subscriber<? super String> subscriber) {
            ValueUpdateListener listener = new ValueUpdateListener() {

                @Override
                public void onValueChanged(@NonNull String value) {
                    if (subscriber.isUnsubscribed()) {
                        registerListener.unregisterListener(this);
                    } else {
                        subscriber.onNext(value);
                    }
                }
            };

            registerListener.registerListener(listener);
        }
    });
}

Now you just have to subscribe:

observableListenerWrapper().subscribe(value -> {
    // do something with the new value
});

Note that the listener will be automatically unregistered if the method

1
onValueChanged
is called and the observable is unsubscribed.

Migrate to Android Studio 2.3

![Android Studio Logo]({{site.baseurl}}/images/android_studio_logo.png)### New featuresAndroid Studio 2.3 has finally been released in th...… Continue reading

Android Auto Fit TextView

Published on September 09, 2016

Workshop su Google, Android e IoT

Published on June 18, 2016