Implementation of file download progress of retrofit + rxjava
preface
Recently, I was learning about retrofit. Although retrofit does not provide a callback of file download progress, the underlying layer of retrofit relies on okhttp. In fact, it is necessary to realize okhttp's monitoring of download progress. There is a progress in okhttp's official demo Java file, as the name suggests. Click me to check.
preparation
This paper adopts dagger2, retrofit and rxjava.
Transform ResponseBody
The default ResponseBody of okhttp3 does not know the progress information, so it needs to be modified. You can use the interface to monitor progress information. Rxbus is used here to send fileloadevent object to update the download progress in real time. Let's start with the modified progressresponsebody.
Er, I'm also learning about okio. This code is copied from the official demo, but rxbus is used to send fileloadevent object in real time.
FileLoadEvent
Fileloadevent is very simple, including the current loaded progress and the total file size.
RxBus
Rxbus looks like a library, but it is not a library, but a pattern. Its idea is to use rxjava to implement eventbus, so that you no longer need to use Otto or eventbus. Click me to see the details.
FileCallBack
So, here's the point. There are actually five methods in the code that need to be rewritten. Well, these methods can be simplified. The progress () method has two parameters, progress and total, which respectively represent the downloaded size and total size of the file. We can constantly update these two parameters to the UI.
Start downloading
Use your own progressresponsebody
Intercept the response through the interceptor of okhttpclient, and set our progressreconsebody to monitor the progress.
Build retrofit
Request interface
Execute request
Perform network requests in the presenter layer.
The request network is invoked through the V layer dependency injection presenter object. After calling the network, the V layer is called to update the UI operation.
Step on the pit.
The dependent retrofit version must be consistent!!! Too much is tears.
When saving the file, use the doonnext operator of rxjava, and switch the subsequent UI update operation to the UI thread.
summary
There seems to be a lot of code, but the process is not complicated:
When saving a file, call the read method of forwardingsource to send a real-time fileloadevent object through rxbus.
Filecallback subscribes to the fileloadevent sent by rxbus. Update the UI by receiving the download progress and total file size in fileloadevent.
After downloading the saved file, cancel the subscription to prevent memory leakage.
Demo address: https://github.com/AirMiya/DownloadDemo