I am downloading a file via OkHttp3. When I get back the Response response
as a result of calling .newCall().execute()
, I am writing the response to the Android device's disk as so:
//https://stackoverflow.com/a/29012988/4672234
File targetFile = MyFileManager.getMyFile(context);
BufferedSink sink = Okio.buffer(Okio.sink(targetFile));
sink.writeAll(response.body().source());
sink.close();
I'm observing strange behavior in some clients where the file will be entirely downloaded, then while they are attempting to write the file to disk, there is a network error. At that time the write to disk is interrupted and I'm left with only part of the file on the file system.
I don't mind the network errors - this is unsurprising as several clients are in very poor network coverage. And with cheap devices. I want to avoid a situation where the network connection is trying to be kept open while the device is writing to disk.
I realize I maybe postulating - is OkHttp leaving the http connection open while I'm writing the file to disk? If so how do I work around this issue - read all of the data into memory immediately, close the OkHttp response, then write that to disk?