Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

278
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda