Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

277
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda