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:
We can create an Observable like this:
Now you just have to subscribe:
Note that the listener will be automatically unregistered if the method onValueChanged is called and the observable is unsubscribed.