android - RxJava 取消对 'Single.fromCallable' 的请求,disposable.clear 导致 InterruptedIOException
问题描述
我在我的应用程序中使用 RxJava 和 AWS API Gateway。
代码在这里:
@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)
);
问题是,当用户在搜索过程中过于频繁地更改文本并且 api 调用已经在进行中时,我想在发送新命中之前取消先前的调用,因为我不希望由于查询更改而响应先前的命中。
我也尝试过使用disposable.cancel,但它给出了错误
'ApiClientException: java.io.InterruptedIOException: thread interrupted'
我怎样才能实现我的目标来保存我的命中?任何想法都将是可观的。
谢谢
解决方案
某些 API 通过引发无法中继的异常来响应取消。如果此类崩溃是一致的,例如您总是InterruptedIOException
从此类 API 中获得,您可以专门忽略此类异常,因此 RxJava 不会知道它们。
这有点难以实现,fromCallable
因为您必须返回非空值,但您可能无法创建所涉及类型的实例。因此,我建议使用 create:
Single.create(emitter -> {
try {
emitter.onSuccess(client.postSearch(keyword,offset));
} catch (InterruptedIOException ex) {
// ignore
} catch (Throwable ex) {
emitter.onError(ex);
}
});
编辑如果你可以创建 ąn SearchResponse
,你可以留下fromCallable
:
Single.fromCallable(() -> {
try {
return client.postSearch(keyword,offset);
} catch (InterruptedIOException ex) {
// fromCallable won't actually emit this
return new SearchResponse();
}
});
推荐阅读
- mysql - SQL 中的工作台
- duplicates - 如果 pdf 包含“重复的书签”,如何使用 itext 7 按书签拆分 pdf 文件
- c# - 如何一次从 ASP.Net webAPI modelState 中获取所有错误?
- r - 我无法在 R 中从 github 安装“loadR”(climate4R)
- c++ - 是否是clang中的一个错误,它在不使用nested-name-specifier的情况下定义了命名空间的成员
- if-statement - 如何编码:“如果(A 为真)和(当 C 为真时 B 为真)”
- javascript - 使用 JavaScript 检查单选按钮状态
- linux - 如何修复 MongoDB 致命断言 28595 错误?
- python - 如何使用 matplotlib 在 Python 中绘制 f(x) = e^x - 4x^3 + 1?
- java - 是否有与 java 的`getDeclaredMethod()` 等效的方法来测试 Typescript 中类的私有方法?