Created
June 3, 2020 19:50
-
-
Save kobeumut/f211d94563aa83e22d6eb9915b5425e6 to your computer and use it in GitHub Desktop.
Save file extension with retrofit and coroutine
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
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 = [email protected]() | |
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