从正常的Java事件创建可观察 [英] Creating Observable from normal Java events
问题描述
从古典的Java事件模式中创建一个Rx-Java c> 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.
有更好的解决方案吗?
要求:
-
使用事件模式的现有实现而不改变它们(如果我正在控制该代码,我可以写它返回
可观察
我需要)
如果/当源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.
推荐答案
我不认为有可能为每个可能的事件创建一个通用的可观察值,但是您可以随时随地使用它们。
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.
这篇关于从正常的Java事件创建可观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!