Issue
I am using a coroutine inside a fragment to handle a network request. However when I navigate away to another fragment the UI from the next fragment is blank and nothing loads. I am using lifecycle scope so I thought the coroutine would be cancelled/cleaned up on destoyed but the only way the UI returns is if I comment out the coroutine.
lifecycleScope.launch(context = Dispatchers.IO){
if (pdfResponse != null) {
try {
file = getTempPdfFile(pdfResponse)
} catch (e: Exception) {
}
}
}
private fun getTempPdfFile(body: ResponseBody): File? {
return try {
val file = File.createTempFile("myfile", ".pdf")
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
try {
val fileReader = ByteArray(4096)
var fileSizeDownloaded: Long = 0
inputStream = body.byteStream()
outputStream = FileOutputStream(file)
while (true) {
val read: Int = inputStream.read(fileReader)
if (read == -1) {
break
}
outputStream.write(fileReader, 0, read)
fileSizeDownloaded += read.toLong()
}
outputStream.flush()
return file
} catch (e: IOException) {
null
} finally {
inputStream?.close()
outputStream?.close()
}
} catch (e: IOException) {
null
}
}
Can anyone help me diagnose the cause of this issue?
Solution
I created a suspend function in the viewmodel like this:
suspend fun createPdfFile() =
withContext(Dispatchers.IO) {
if (getPdfResponse() != null) {
try {
file = getPdfResponse()?.let { getTempPdfFile(it) }
} catch (e: Exception) {
}
}
}
Then in the view I called it using :
lifecycleScope.launch(Dispatchers.Main) {
createPdfFile()
}
Answered By - AndroidDev123
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.