Search code examples
androidkotlincoroutinekotlinx.coroutineskotlin-coroutines

Coroutines running on the main thread instead of background


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


Solution

  • 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 invoking convertImageFileToBase64 function to upload generatedBase64 to the server, i.e use withContext(Dispatchers.IO):

    launch {
        withContext(Dispatchers.IO) {
            generatedBase64 = convertImageFileToBase64(file)
            //upload generatedBase64 to server here
        }
        // do UI stuff here, e.g. show some message, set text to TextView etc.
    }