Member-only story
Android: DownloadFile From Server Using Retrofit — Part 2: Beware with Large Files: Use @Streaming!
If you’re downloading a large file, Retrofit would try to move the entire file into memory. In order to avoid that, we’ve to add a special annotation to the request declaration:
@Streaming
@GET
Call<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);
The @Streaming
declaration doesn't mean you're watching a Netflix file. It means that instead of moving the entire file into memory, it'll pass along the bytes right away. But be careful, if you're adding the @Streaming
declaration and continue to use the code above, Android will trigger a android.os.NetworkOnMainThreadException
.
Thus, the final step is to wrap the call into a separate thread, for example with a lovely ASyncTask:
You can still use the same writeResponseBodyToDisk()
method. If you remember the @Streaming
declaration and this snippet, you can download even large files with Retrofit efficiently.
Part 1: https://medium.com/@imstudio/android-downloadfile-from-server-using-retrofit-part-1-817ae8caa169
Thanks for reading, please feel free to comment with this post.