Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit Closing Response Body

I've been getting this error:

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

So I went on and close the responses I get.

response.body().close()

Problem is if the response.body() is already converted to a custom class, there's no close method available. Also I tried calling raw and gives 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 do I close it?

like image 481
Kim Montano Avatar asked Sep 14 '16 04:09

Kim Montano


1 Answers

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 it will solve your issue.

like image 70
Soham Avatar answered Sep 20 '22 11:09

Soham