Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 750
Ofek Ron Avatar asked May 24 '26 16:05

Ofek Ron


1 Answers

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 + "]");
                }
            });
like image 156
Bartek Lipinski Avatar answered May 27 '26 06:05

Bartek Lipinski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!