Wrapping event listeners in Observables

 ̄綄美尐妖づ 提交于 2020-01-25 21:41:30

问题


I've seen a lot of examples of how to turn finite things like arrays or Iterables into Observables, 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.

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

回答1:


using Observable.create() is indeed a correct way.

However, with RxJava2 the default way is to extend an Observable, you can see this answer for greater details.

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.



来源:https://stackoverflow.com/questions/44833118/wrapping-event-listeners-in-observables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!