I have an application in which user picks a pdf from file explorer and then I need to convert that pdf to base 64.
Following is my code to convert pdf to base64
private fun convertImageFileToBase64(imageFile: File?): String {
return FileInputStream(imageFile).use { inputStream ->
ByteArrayOutputStream().use { outputStream ->
Base64OutputStream(outputStream, Base64.DEFAULT).use { base64FilterStream ->
inputStream.copyTo(base64FilterStream)
base64FilterStream.flush()
outputStream.toString()
}
}
}
}
so in the onActivityResult where I am getting the pdf file I am writing the following code
launch {
withContext(Dispatchers.IO) {
generatedBase64 = convertImageFileToBase64(file)
}
//upload generatedBase64 to server
}
But the code runs on the main thread instead of background thread and my ui freezes for some time if the pdf file is large. I also tried AsyncTask and tried performing the conversion in doInBackground method but I am facing the same issue
If you use something like
Dispatchers.Main + Job()as a context to launch the coroutine then in place where you have the comment "upload generatedBase64 to server" it will run on the main thread. You need to switch contexts like you did for invokingconvertImageFileToBase64function to uploadgeneratedBase64to the server, i.e usewithContext(Dispatchers.IO):