Ofek Ron Ofek Ron - 6 months ago 91
Android Question

how to escape this callback hell using RxJava

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


Im trying to use the great Android-ReactiveLocation to implement a "set" like operation for a geofence - e.g if already exists then clear it and then set it to the desired location so that there will always be up to one geofence.

Well I am also trying to learn RxJava while at it, so i heard RxJava can solve callback hell problems, so how can it do so in my case?

Thanks!

Answer

When you want to use consecutive subscriptions, you should use flatMap operator. This way your problem can be simplified to this:

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 + "]");
                }
            });