RxJava: convert a listener into an Observable

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 ValueUpdateListener and an object ValueUpdater that will call our listener:

publicinterfaceValueUpdateListener{voidonValueChanged(@NonNullStringvalue);}publicclassValueUpdater{// in some point of the class...publicvoidregisterListener(ValueUpdateListenerlistener){//...};publicvoidunregisterListener(ValueUpdateListenerlistener){//...};}