如何使用RxJava来逃避这个回调地狱

时间:2016-05-29 19:16:35

标签: android rx-java

subscriptionSet = provider.removeGeofences(mGeofencePendingIntent).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Status>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "onError() called with: " + "e = [" + e + "]");
            }

            @Override
            public void onNext(Status status) {
                Prefs.geofence.clear();
                subscriptionAdd = statusObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Status>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onError() called with: " + "e = [" + e + "]");
                    }

                    @Override
                    public void onNext(Status status) {
                        Prefs.geofence.set(...);
                    }
                });
            }
        });

我试图使用伟大的Android-ReactiveLocation来实现地理围栏的“设置”操作 - 例如,如果已经存在,则清除它然后将其设置到所需的位置,以便始终最多一个地理围栏。

好吧我也在尝试学习RxJava,所以我听说RxJava可以解决回调地狱问题,所以在我的情况下它怎么能这样做呢?

谢谢!

1 个答案:

答案 0 :(得分:3)

如果要使用连续订阅,则应使用flatMap运算符。这样你的问题可以简化为:

subscription = provider.removeGeofences(mGeofencePendingIntent)
            .flatMap(new Func1<Status, Observable<Status>>() {
                @Override
                public Observable<Status> call(Status status) {
                    //after the first subscription
                    Prefs.geofence.clear();
                    return statusObservable;
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<Status>() {
                @Override
                public void call(Status status) {
                    //after the second subscription
                    Prefs.geofence.set(...);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    Log.d(TAG, "onError() called with: " + "e = [" + e + "]");
                }
            });