在 Observables 中包装事件监听器 [英] Wrapping event listeners in Observables
问题描述
我看过很多关于如何将有限的事物(如数组或 Iterable
s)转换为 Observable
s 的例子,但我不确定我是否理解如何将Observable
用像事件接收器这样的活动且有效无界的东西制作出来.我研究了 RxJava2 文档并提出了这个,以 Android LocationListener
为例.
I've seen a lot of examples of how to turn finite things like arrays or Iterable
s into Observable
s, but I'm not sure I understand how to make an Observable
out of something live and effectively unbounded like an event receiver. I studied the RxJava2 docs and came up with this, using an Android LocationListener
as an example.
是否有更简单和/或更正确的方法来做到这一点?我知道RxBus"概念,但这似乎是一种坚持旧事件总线范式的方式.
Is there a simpler and/or more correct way to do this? I'm aware of the "RxBus" concept, but it seems like a way of clinging to the old event bus paradigm.
final Observable<Location> locationObservable = Observable.create(new ObservableOnSubscribe<Location>() {
final LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
@Override
public void subscribe(final ObservableEmitter<Location> emitter) throws Exception {
final LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
emitter.onNext(location);
}
@Override
public void onStatusChanged(final String s, final int i, final Bundle bundle) {
// TODO ???
}
@Override
public void onProviderEnabled(final String s) {
// TODO ???
}
@Override
public void onProviderDisabled(final String s) {
// TODO ???
}
};
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
emitter.setCancellable(new Cancellable() {
@Override
public void cancel() throws Exception {
mLocationManager.removeUpdates(listener);
}
});
emitter.setDisposable(new Disposable() {
private AtomicBoolean mDisposed;
@Override
public void dispose() {
if(mDisposed.compareAndSet(false, true)) {
mLocationManager.removeUpdates(listener);
}
}
@Override
public boolean isDisposed() {
return mDisposed.get();
}
});
}
});
推荐答案
using Observable.create()
确实是一个正确的方法.
using Observable.create()
is indeed a correct way.
但是,对于 RxJava2,默认方式是扩展 Observable,您可以查看此答案了解更多详情.
However, with RxJava2 the default way is to extend an Observable, you can see this answer for greater details.
关于您的实施的一些评论:
- 没有必要同时设置Cancellable
和Disposable
,因为后者会取消/处理第一个,你可以看到它们之间的区别此处.
- 我认为最好的做法是在开始收听更新之前注册可取消/一次性注册,以防止出现奇怪的边缘情况.
some comments though regarding your implementation:
- there is no point setting both Cancellable
and Disposable
, as the later one will cancel/dispose the first one, you can see the difference between them here.
- I think it's best practice, to register cancellable/disposable before you start listening to update, in order to prevent weird edge cases races.
这篇关于在 Observables 中包装事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!