Reputation: 2142
I'm using RxJava along with AWS API Gateway in my app.
The code is here:
@Override
public Single<SearchResponse> searchPostsApiCall(String keyword, String offset) {
return Single.fromCallable(() -> client.postSearch(keyword,offset));
}
// to call api
getCompositeDisposable().add(searchPostsApiCall(keyword,offset)
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(response -> onResponseReceived(response, offset, finalType), this::onError)
);
The issue is that when user during search changes text too frequently and api call is already in process then i want to cancel previous call before sending new hit as i don't want response of previous hit due to changed query.
I tried using disposable.cancel too but it gives error
'ApiClientException: java.io.InterruptedIOException: thread interrupted'
How can i achieve my target to save my hits? Any idea will be appreciable.
Thanks
Upvotes: 3
Views: 1104
Reputation: 69997
Some APIs respond to cancellation by throwing an exception that can't be relayed. If such crashes are consistent, such as you always get InterruptedIOException
from such APIs, you can ignore such exceptions specifically and thus RxJava won't know about them.
This is somewhat difficult to achieve via fromCallable
as you have to return something non-null but you may not be able to create an instance of the type involved. Therefore, I suggest using create:
Single.create(emitter -> {
try {
emitter.onSuccess(client.postSearch(keyword,offset));
} catch (InterruptedIOException ex) {
// ignore
} catch (Throwable ex) {
emitter.onError(ex);
}
});
Edit If you can create ąn SearchResponse
, you can stay with fromCallable
:
Single.fromCallable(() -> {
try {
return client.postSearch(keyword,offset);
} catch (InterruptedIOException ex) {
// fromCallable won't actually emit this
return new SearchResponse();
}
});
Upvotes: 1