Reputation: 39
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 :
- API_CALL_1 fetching the View_1 Results
- User swipes a View_2
- API_CALL_2 fetching the View_2 Results
- 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
Reputation: 97
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:
Upvotes: 1
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