从普通 Java 事件创建 Observable
从经典 Java 事件模式创建 Rx-Java Observable
的最佳方法是什么?也就是说,给定
What is the best way to create an Rx-Java Observable
from the classical Java event pattern? That is, given
class FooEvent { ... }
interface FooListener {
void fooHappened(FooEvent arg);
}
class Bar {
public void addFooListener(FooListener l);
public void removeFooListener(FooListener l);
}
我要实现
Observable<FooEvent> fooEvents(Bar bar);
我想出的实现是:
Observable<FooEvent> fooEvents(Bar bar) {
return Observable.create(new OnSubscribeFunc<FooEvent>() {
public Subscription onSubscribe(Observer<? super FooEvent> obs) {
FooListener l = new FooListener() {
public void fooHappened(FooEvent arg) {
obs.onNext(arg);
}
};
bar.addFooListener(l);
return new Subscription() {
public void unsubscribe() {
bar.removeFooListener(l);
}
};
}
});
}
不过,我不是很喜欢:
很冗长;
it's quite verbose;
每个 Observer
都需要一个监听器(理想情况下,如果没有观察者,则应该没有监听器,否则只有一个监听器).这可以通过将观察者计数保留为 OnSubscribeFunc
中的一个字段,在订阅时递增,在取消订阅时递减.
requires a listener per Observer
(ideally there should be no listeners if there are no observers, and one listener otherwise). This can be improved by keeping an observer count as a field in the OnSubscribeFunc
, incrementing it on subscribe and decrementing on unsubscribe.
有没有更好的解决方案?
Is there a better solution?
要求:
使用现有的事件模式实现而不更改它们(如果我正在控制该代码,我已经可以编写它以返回我需要的
Observable
).
如果/当源 API 更改时会出现编译器错误.不能使用 Object
而不是实际的事件参数类型或属性名称字符串.
Getting compiler errors if/when the source API changes. No working with Object
instead of actual event argument type or with property name strings.
推荐答案
我认为没有办法为每个可能的事件创建一个通用的 observable,但你当然可以在任何需要的地方使用它们.
I don't think there's a way to create a generic observable for every possible event, but you can certainly use them wherever you need.
RxJava 源代码有一些方便的示例,说明如何从鼠标事件、按钮事件等创建可观察对象.看看这个类,它从 KeyEvents 创建它们:KeyEventSource.java.
The RxJava source has some handy examples of how to create observables from mouse events, button events, etc. Take a look at this class, which creates them from KeyEvents: KeyEventSource.java.
相关文章