我遵循了这篇博客文章:
https://medium.com/@PaulinaSadowska/display-progress-of-multipart-request-with-retrofit-and-rxjava-23a4a779e6ba,然后进行了以下调整以显示总进度而不是单独文件的进度:
private fun prepareFileParts(reportAttachments: MutableList<ReportAttachment>, emitter: FlowableEmitter<Double>): List<MultipartBody.Part> {
val multiPartBodyList = mutableListOf<MultipartBody.Part>()
var offset = 0L
var totalLength = 0L
for (attachment in reportAttachments) {
val file = File(attachment.filePath)
totalLength += file.length()
}
for (attachment in reportAttachments) {
val file = File(attachment.filePath)
val mimeType = attachment.mimeType
val countingRequestBody = createCountingRequestBody(file, mimeType, emitter, offset, totalLength)
offset += file.length()
val multipartBody = MultipartBody.Part.createFormData("file", file.name, countingRequestBody)
multiPartBodyList.add(multipartBody)
}
return multiPartBodyList
}
private fun createCountingRequestBody(file: File, mimeType: String, emitter: FlowableEmitter<Double>, offset: Long, totalLength: Long): RequestBody {
val requestBody = RequestBody.create(MediaType.parse(mimeType), file)
return CountingRequestBody(requestBody, object : CountingRequestBody.Listener {
override fun onRequestProgress(bytesWritten: Long, contentLength: Long) {
val progress: Double = 1.0 * (offset + bytesWritten) / totalLength
emitter.onNext(progress)
}
})
}
如果你想的话,你也可以创建一个拦截器并将其添加到你的OkHttpClient
中。这样默认情况下就会跟踪所有的出站API调用。它看起来会像这样:
class UploadProgressInterceptor(private val progressListener: CountingRequestBody.Listener) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
if (originalRequest.body() == null) {
return chain.proceed(originalRequest)
}
val requestBody = originalRequest.body()
requestBody?.let {
val progressRequest = originalRequest.newBuilder()
.method(originalRequest.method(), CountingRequestBody(it, progressListener))
.build()
return chain.proceed(progressRequest)
}
return chain.proceed(originalRequest)
}