Last active
January 19, 2020 19:35
-
-
Save pranay1494/6ea6f12bb2e37c8369eccf7d486003e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.reactivex.subjects.PublishSubject | |
import okhttp3.MediaType | |
import okhttp3.RequestBody | |
import okio.BufferedSink | |
import java.io.File | |
import java.io.FileInputStream | |
import java.lang.Exception | |
class ProgressEmittingRequestBody constructor(val mediaType: String, val file: File) : RequestBody() { | |
val progressSubject = PublishSubject.create<Int>() | |
override fun contentType(): MediaType? = MediaType.parse(mediaType) | |
override fun writeTo(sink: BufferedSink) { | |
val inputStream = FileInputStream(file) | |
val buffer = ByteArray(BUFFER_SIZE) | |
var uploaded: Long = 0 | |
val fileSize = file.length() | |
try { | |
while (true) { | |
val read = inputStream.read(buffer) | |
if (read == -1) break | |
uploaded += read | |
sink.write(buffer, 0, read) | |
val progress = (((uploaded / fileSize.toDouble())) * 100).toInt() | |
progressSubject.onNext(progress) | |
} | |
} catch (e: Exception) { | |
e.printStackTrace() | |
progressSubject.onError(e) | |
} finally { | |
inputStream.close() | |
} | |
} | |
companion object { | |
const val BUFFER_SIZE = 1024 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment