当与Retrofit RxJavaCallAdapterFactory一起使用时,Okhttp会忽略Dispatcher设置

sah*_*har 6 android rx-java retrofit2 okhttp3

考虑以下OkHttp和Retrofit的初始化:

public static SomeServiceRestInterface newRestService(String apiUrl) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(apiUrl)
                    .client(createOkHttpClient())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                    .addConverterFactory(createGsonConverter())
                    .build();
            return retrofit.create(SomeServiceRestInterface.class);
}

private static OkHttpClient createOkHttpClient() {
                    Dispatcher dispatcher = new Dispatcher();
                    dispatcher.setMaxRequestsPerHost(1);
                    dispatcher.setMaxRequests(1);
                    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                                .dispatcher(dispatcher).build()
}
Run Code Online (Sandbox Code Playgroud)

在测试其余调用时,我注意到Okhttp根本不遵守setMaxRequestsPerHost或setMaxRequests设置.以下是同时发送的3个请求的日志:

23/07 04:14:22.668 [RxIoScheduler-4] DEBUG - --> POST https://XXX/1 http/1.1
23/07 04:14:22.668 [RxIoScheduler-4] DEBUG - Content-Length: 0
23/07 04:14:22.668 [RxIoScheduler-4] DEBUG - --> END POST (0-byte body)
23/07 04:14:22.672 [RxIoScheduler-7] DEBUG - --> POST https://XXX/2 http/1.1
23/07 04:14:22.673 [RxIoScheduler-7] DEBUG - Content-Length: 0
23/07 04:14:22.673 [RxIoScheduler-7] DEBUG - --> END POST (0-byte body)
23/07 04:14:22.676 [RxIoScheduler-6] DEBUG - --> POST https://XXX/3 http/1.1
23/07 04:14:22.677 [RxIoScheduler-6] DEBUG - Content-Length: 0
23/07 04:14:22.677 [RxIoScheduler-6] DEBUG - --> END POST (0-byte body)
Run Code Online (Sandbox Code Playgroud)

其中XXX是同一个域,1/2/3是不同的路径.

我不确定为什么,但我认为这可能与addCallAdapterFactory中设置的RxJava Scheduler有关.

这是一个错误吗?还是我错过了什么?

我正在使用okhttp 3.4.1,并改进2.1.0.

sah*_*har 5

在这个问题上引用杰克沃顿的话:

Observable for Retrofit的实现依赖于应用的Scheduler同步执行请求以进行任何必要的限制.如果您需要OkHttp的Dispatcher的限制,那么您将必须编写一个使用Call.enqueue而不是Call.execute的自定义CallAdapter for Observable.

我们目前没有计划支持这一点,尽管基于假设的OkHttp v4构建的Retrofit v3可能会使其成为默认值(尽管这还有很长的路要走).

如果您使用Retrofit的Call并调用.execute(),或者甚至使用带有.execute()的OkHttp调用,则会出现这种情况.