如何使用 Retrofit 2.0 限制并行请求?

Ale*_*ndr 5 android retrofit2

我的目标是通过抛出异常来限制并行执行请求的数量。

例如,我只想要一个执行请求:

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 实现它?

mit*_*rop 2

我不确定抛出 anException是最好的方法,但我不知道你的用例,所以我不会讨论这一点:)

不管怎样,@Daniel 的评论实际上指出了一个很好的方向。如果您使用retrofitwith OkHttp,则它将OkHttpClient处理“并发请求”内容。阅读文档,您可以看到 OkHttp 使用 aDispatcher来处理并行异步请求(Dispatcher 文档)。

所以有两个有趣的点是:

  1. 方法setMaxRequests(int maxRequests):定义最大并发请求数
  2. Method executed(RealCall call): 实际执行一个请求

我认为你可以这样做来实现你的目标:

  1. 创建自定义Dispatcher
  2. executed(RealCall call)如果当前请求的数量优于,则重写抛出异常的方法maxRequests
  3. Dispatcher使用您正在OkHttpClient使用的自定义retrofit