Skip to content

Commit

Permalink
converted ProgressResponseBody to Kt
Browse files Browse the repository at this point in the history
  • Loading branch information
Zeyad-37 committed Oct 28, 2018
1 parent 5f79a2d commit dfe2281
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ abstract class ProgressInterceptor(private val progressListener: ProgressListene
val originalResponse = chain.proceed(chain.request())
val responseBuilder = originalResponse.newBuilder()
if (isFileIO(originalResponse)) {
responseBuilder.body(ProgressResponseBody(originalResponse.body(), progressListener))
responseBuilder.body(originalResponse.body()?.let { ProgressResponseBody(it, progressListener) })
} else {
responseBuilder.body(originalResponse.body())
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.zeyad.usecases.network

import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*
import java.io.IOException

/**
* @author by ZIaDo on 7/11/17.
*/
internal class ProgressResponseBody(private val responseBody: ResponseBody, private val progressListener: ProgressListener) : ResponseBody() {
private lateinit var bufferedSource: BufferedSource

override fun contentType(): MediaType? {
return responseBody.contentType()
}

override fun contentLength(): Long {
return responseBody.contentLength()
}

override fun source(): BufferedSource {
if (!::bufferedSource.isInitialized) {
bufferedSource = Okio.buffer(source(responseBody.source()))
}
return bufferedSource
}

private fun source(source: Source): Source {
return object : ForwardingSource(source) {
var totalBytesRead = 0L

@Throws(IOException::class)
override fun read(sink: Buffer, byteCount: Long): Long {
val bytesRead = super.read(sink, byteCount)
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += if (bytesRead != -1L) bytesRead else 0
progressListener.update(totalBytesRead, responseBody.contentLength(),
bytesRead == -1L)
return bytesRead
}
}
}
}

0 comments on commit dfe2281

Please sign in to comment.