Vinay KG
Vinay KG

Reputation: 39

Android RxJava Cancel the old request

I am new to Rxjava and exploring the possibilities and need help in below described scenario.

Step 1 : Swipe the View
Step 2 : Make an API Call to fetch Data

The above steps are repeated for the number of Views.

Problem :

  1. API_CALL_1 fetching the View_1 Results
  2. User swipes a View_2
  3. API_CALL_2 fetching the View_2 Results
  4. View_1 results are returned and populated in View_2 along with View_2 results

I need to cancel the API_CALL_1 request when the API_CALL_2 request. Thanks.

Upvotes: 3

Views: 5785

Answers (3)

You are able to provide 'cancel' logic by using 'switchMap' operator. For example, you want to start/stop loading (Code written in Kotlin).

val loadingObservable = Observable.timer(10, TimeUnit.SECONDS)
val load = PublishSubject.create<Boolean>()
val resultObservable = load.switchMap { if(it) loadingObservable else Observable.never() }

Explanation:

  1. 'loadingObservable' is a timer that simulate long running operation
  2. 'load' is a command from user to start or stop loading. If you want to start loading - send True else False
  3. 'switchMap' operator is designed to dispose previous observable. So it you send True it will start loading. If you send False it will dispose (cancel) previous observable.

Upvotes: 1

shakil.k
shakil.k

Reputation: 1723

a better way is to use switchMap to cancel previous request

Upvotes: 1

Aleksandr
Aleksandr

Reputation: 4936

Class member:

Subscription mSubscription;

Your API call:

if(subscription != null && !subscription.isUnsubscribed()){
    subscription.unsubscribe();
    subscription = null;
}
subscription = doApiCall("some_id")
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {

            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {

            }
        });

So, the main idea of it, that you have to unsubscribe from previous call:

if(subscription != null && !subscription.isUnsubscribed()){
    subscription.unsubscribe();
    subscription = null;
}

Before starting new call

Upvotes: 3

Related Questions