問題描述
從經(jīng)典 Java 事件模式創(chuàng)建 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);
}
我要實(shí)現(xiàn)
Observable<FooEvent> fooEvents(Bar bar);
我想出的實(shí)現(xiàn)是:
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
都需要一個監(jiān)聽器(理想情況下,如果沒有觀察者,則應(yīng)該沒有監(jiān)聽器,否則只有一個監(jiān)聽器).這可以通過將觀察者計數(shù)保留為 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?
要求:
使用現(xiàn)有的事件模式實(shí)現(xiàn)而不更改它們(如果我正在控制該代碼,我已經(jīng)可以編寫它以返回我需要的
Observable
).
如果/當(dāng)源 API 更改時會出現(xiàn)編譯器錯誤.不能使用 Object
而不是實(shí)際的事件參數(shù)類型或?qū)傩悦Q字符串.
Getting compiler errors if/when the source API changes. No working with Object
instead of actual event argument type or with property name strings.
推薦答案
我認(rèn)為沒有辦法為每個可能的事件創(chuàng)建一個通用的 observable,但你當(dāng)然可以在任何需要的地方使用它們.
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 源代碼有一些方便的示例,說明如何從鼠標(biāo)事件、按鈕事件等創(chuàng)建可觀察對象.看看這個類,它從 KeyEvents 創(chuàng)建它們: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.
這篇關(guān)于從普通 Java 事件創(chuàng)建 Observable的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!