3

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.

Nikhil
  • 3,711
  • 8
  • 32
  • 43
Vinay KG
  • 39
  • 1
  • 8
  • Every RxJava network request you have one subscription, Unsubscribe the request next View swiped http://stackoverflow.com/a/34205073/3629732 – Rajesh Nov 14 '16 at 05:55
  • @RajeshRajendiran, Is there any way to automatically does unsubscription like switchMap or anything similar . . . – Vinay KG Nov 14 '16 at 05:58
  • switchMap,flatMap all are operators in RxJava (Just like + , - , *...) the base is observable more you can see http://reactivex.io/documentation/operators.html – Rajesh Nov 14 '16 at 06:04

3 Answers3

3

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

Aleksandr
  • 4,906
  • 4
  • 32
  • 47
1

a better way is to use switchMap to cancel previous request

shakil.k
  • 1,623
  • 5
  • 17
  • 27
1

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.