What is the best way to create an Rx-Java Observable
from the classical Java event pattern? That is, given
class FooEvent { ... }
interface Foo
Your implementation is absolutely correct.
it's quite verbose
It gets much less verbose with lambdas (example for RxJava 2):
Observable fooEvents(Bar bar) {
return Observable.create(emitter -> {
FooListener listener = event -> emitter.onNext(event);
bar.addFooListener(listener);
emitter.setCancellable(() -> bar.removeFooListener(listener));
});
}
ideally there should be no listeners if there are no observers, and one listener otherwise
You can use share()
operator, which makes your observable hot, i.e. all subscribers share single subscription. It automatically subscribes with the first subscriber, and unsubscribes when last one unsubscribes:
fooEvents(bar).share()