Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!