Skip to content

Instantly share code, notes, and snippets.

@kobeumut
Created June 3, 2020 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobeumut/f211d94563aa83e22d6eb9915b5425e6 to your computer and use it in GitHub Desktop.
Save kobeumut/f211d94563aa83e22d6eb9915b5425e6 to your computer and use it in GitHub Desktop.
Save file extension with retrofit and coroutine
Call<ResponseBody>.saveFile(fileNameWithExt: String, action: (file: File?) -> Unit) {
GlobalScope.launch {
try {
cacheDir.listFiles { _, name -> name.contains("${fileType}.pdf") }?.lastOrNull {
action(it)
true
}?:
withContext(Dispatchers.IO) {
val response = this@saveFile.execute()
val buffer = response.body()?.byteStream()
var file: File? = null
if (buffer != null) {
file = File.createTempFile(fileNameWithExt, null, baseContext?.cacheDir)
if (file != null) {
buffer.copyStreamToFile(file)
}
}
action(file)
}
} catch (e: Exception) {
Log.e("error", e.message ?: "")
}
}
}
private fun InputStream.copyStreamToFile(outputFile: File) {
this.use { input ->
val outputStream = FileOutputStream(outputFile)
outputStream.use { output ->
val buffer = ByteArray(4 * 1024)
while (true) {
val byteCount = input.read(buffer)
if (byteCount < 0) break
output.write(buffer, 0, byteCount)
}
output.flush()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment