我的目标是通过抛出异常来限制并行执行请求的数量。
例如,我只想要一个执行请求:
someApi.getUser(
result -> print("ok: " + result), exception -> print("error: " + exception)
); // this request will be executed in 5 seconds
someApi.getServerInfo(
result -> print("ok: " + result), exception -> print("error: " + exception)
); // there I want to catch exception like ExecutorIsBusy
Run Code Online (Sandbox Code Playgroud)
如何使用 Retrofit 2.0 实现它?
我不确定抛出 anException是最好的方法,但我不知道你的用例,所以我不会讨论这一点:)
不管怎样,@Daniel 的评论实际上指出了一个很好的方向。如果您使用retrofitwith OkHttp,则它将OkHttpClient处理“并发请求”内容。阅读文档,您可以看到 OkHttp 使用 aDispatcher来处理并行异步请求(Dispatcher 文档)。
所以有两个有趣的点是:
setMaxRequests(int maxRequests):定义最大并发请求数executed(RealCall call): 实际执行一个请求我认为你可以这样做来实现你的目标:
Dispatcher类executed(RealCall call)如果当前请求的数量优于,则重写抛出异常的方法maxRequestsDispatcher使用您正在OkHttpClient使用的自定义retrofit| 归档时间: |
|
| 查看次数: |
3670 次 |
| 最近记录: |