Handling Switch between API call or Cancel previous API call and make a new one
There is the scenario when we have to switch between API calls or cancel current API call and make a new API call.
Example :
1. During pagination, you make the API call to fetch more data and then you click on some filter. Based on the filter you have to cancel previous API call and make new API call.
2. When implementing instant search i.e. when user types in a textbox and results appear in near real-time with each keystroke. So, in this case, we want to cancel previous API call
So all of you are thinking about how can we achieve this.
Thanks to SwitchMap operator
We have a SwitchMap operator.
SwitchMap should be used when only results from the last Observable matter.switchMap
will subscribe to the lastObservable
it encounters and unsubscribes from all previousObservable
.
I will take the example of a switch between API calls during pagination
Firstly I will take publishSubject ( Subject can act as both observer and observable). PublishSubject that, once an Observer
has subscribed, emits all subsequently observed items to the subscriber.
PublishSubject<Boolean> filterSwitch = PublishSubject.create();
Make method in Presenter/ViewModel to set value in filterSwitch
void switchApiCall(boolean isFilterApplied) {
filterSwitch.onNext(isFilterApplied);
}
Call this method from view/Activity based on filter status. If applied then pass true else pass false.
void subscribeToStoreSubject() {
disposable = filterSwitch.switchMap((Function<Boolean, ObservableSource<T>>) isFilterApplied -> {
return api.fetchMoreData()})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(//do your stuff );
}
}
So Whenever a new value is pushed to filterSwitch, it cancels previous API call and makes new API call based on isFilterApplied value.
You can pass other params as well in API call based on isFilterApplied value.
Soon I will post more articles on android, core java.
till then happy learning… :)