我的目标是通过抛出异常来限制并行执行请求的数量 .
例如,我只想要一个执行请求:
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
如何使用Retrofit 2.0实现它?
2 回答
我不确定抛出
Exception
是最好的方法,但我不知道你的用例所以我不会讨论这一点:)无论如何,@丹尼尔的评论实际上指向了一个相当不错的方向 . 如果您正在使用
retrofit
和OkHttp
,则OkHttpClient
将处理"concurrent requests"内容 . 阅读文档,您可以看到OkHttp使用Dispatcher
来处理并行异步请求(Dispatcher docs) .所以有两点有趣:
方法
setMaxRequests(int maxRequests)
:定义最大并发请求数方法
executed(RealCall call)
:实际执行请求我认为你可以做到这一点来实现你的目标:
创建自定义
Dispatcher
类如果请求的电流数超过
maxRequests
,则覆盖executed(RealCall call)
方法抛出异常使用
OkHttpClient
中使用的自定义Dispatcher
retrofit
使用RxJava并采用上述注释中的方法,这是一个例子:
假设这些操作附加到按钮上 .
我也不是RxJava的专家,因此可能有一个操作员可以使这更容易 .