Creating Observable from normal Java events

前端 未结 4 2057
花落未央
花落未央 2020-12-30 00:15

What is the best way to create an Rx-Java Observable from the classical Java event pattern? That is, given

class FooEvent { ... }

interface Foo         


        
4条回答
  •  有刺的猬
    2020-12-30 00:47

    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()
    

提交回复
热议问题