Closing Response Retrofit Housing

I get this error:

 A connection to ****** was leaked. Did you forget to close a response body?

So, I continued and closed the answers that I receive.

response.body().close()

The problem is that response.body () is already converted to a user class, the available method is not available. I also tried calling raw and gave me an exception:

fetchSomething.enqueue(new Callback<SomethingClass>() {
            @Override
            public void onResponse(Call<SomethingClass> call, Response<SomethingClass> response) {


                //Closes the response body
                response.raw().body().close(); //<--- gives illegalStateException

            }

            @Override
            public void onFailure(Call<SomethingClass> call, Throwable t) {

            }
        });

    }

How to close it?

+4
source share
1 answer

As mentioned here you can do something like below

 ResponseBody body =  response.raw().body();
                if (response.isSuccessful()) {
                    return body.string(); // Closes automatically.
                } else {
                    body.close();
                    return null;
                }

or

ResponseBody body = response.raw().body();
try {
  ...
} finally {
 body.close();
}

Hope this solves your problem.

0
source

Source: https://habr.com/ru/post/1654520/


All Articles