我正在使用绑定(bind)适配器在回收器 View 中加载图像。图像看起来不错。在快速滚动时,我注意到有时会收到来自毕加索的“连接泄漏”消息。

问题出在死图像链接上,将我所有的图像URL硬编码为无指向,将第一对图像滚动出屏幕后,每张图像都不会产生错误。

W/OkHttpClient: A connection to https://s3-eu-west-1.amazonaws.com/ was leaked. Did you forget to close a response body?

该代码基本上是to this sample

绑定(bind)实用程序
object BindingUtils {

@BindingAdapter("imageUrl")
@JvmStatic
fun setImageUrl(imageView: ImageView, url: String) {
    Picasso.with(imageView.context).load(url).into(imageView)
}

XML文件
<ImageView
android:id="@+id/imageview_merchant_background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/primary"
android:scaleType="centerCrop"
app:imageUrl="@{viewModel.background}"/>

摇动
implementation "com.squareup.retrofit2:retrofit:$rootProject.retrofitVersion"
implementation "com.squareup.retrofit2:adapter-rxjava2:$rootProject.retrofitVersion"
implementation "com.squareup.retrofit2:converter-gson:$rootProject.retrofitVersion"
implementation "com.squareup.okhttp3:logging-interceptor:$rootProject.okhttpLoggingVersion"
implementation "com.squareup.picasso:picasso:$rootProject.picassoVersion"

retrofitVersion = '2.3.0'
okhttpLoggingVersion = '3.6.0'
picassoVersion = '2.5.2'

我可以看到一些引用,这些引用需要关闭标准Okhttp请求的连接,但是看到毕加索的load调用是单线的,那怎么可能泄漏呢?

最佳答案

毕加索在后台使用okhttp3来处理其网络请求。请参见此处的毕加索NetworkRequestHandler类的代码:https://github.com/square/picasso/blob/0728bb1c619746001c60296d975fbc6bd92a05d2/picasso/src/main/java/com/squareup/picasso/NetworkRequestHandler.java

有一个处理okhttp请求的加载函数:

@Override public Result load(Request request, int networkPolicy) throws IOException {
    okhttp3.Request downloaderRequest = createRequest(request, networkPolicy);
    Response response = downloader.load(downloaderRequest);
    ResponseBody body = response.body();

    if (!response.isSuccessful()) {
      body.close();
      throw new ResponseException(response.code(), request.networkPolicy);
    }

    // Cache response is only null when the response comes fully from the network. Both completely
    // cached and conditionally cached responses will have a non-null cache response.
    Picasso.LoadedFrom loadedFrom = response.cacheResponse() == null ? NETWORK : DISK;

    // Sometimes response content length is zero when requests are being replayed. Haven't found
    // root cause to this but retrying the request seems safe to do so.
    if (loadedFrom == DISK && body.contentLength() == 0) {
      body.close();
      throw new ContentLengthException("Received response with 0 content-length header.");
    }
    if (loadedFrom == NETWORK && body.contentLength() > 0) {
      stats.dispatchDownloadFinished(body.contentLength());
    }
    InputStream is = body.byteStream();
    return new Result(is, loadedFrom);
  }

我对Picasso项目不太熟悉,但是似乎响应主体对象并不是在所有情况下都处于关闭状态。您可能已经发现了毕加索中的错误,并且可能想在毕加索的github上提出问题

08-18 04:32