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

149
Visualizações
Suspend function blocks main thread

I'm having a hard time understanding coroutines. This is a very simple setup. Both longComputation and delay are suspend functions. The first one blocks the main thread, the latter doesn't. Why?

CoroutineScope(Dispatchers.Main).launch {
    val result = longComputation() // Blocks
    delay(10_000) // Doesn't block
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

That depends. What does longComputation do exactly? When you mark a function as suspend, this does not mean you can't include blocking code in it. For instance, have a look at this one:

suspend fun blockingSuspendFunction(){
    BigInteger(1500, Random()).nextProbablePrime()
}

The code inside the suspend function is obviously something that utilizes the CPU and blocks the caller. By convention, this should not be done because if you call a suspend function, you expect it to not block the thread:

Convention: suspending functions do not block the caller thread. (https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761)

To make such a function "behave as a suspending function", the blocking has to be dispatched onto another worker thread, which (by recommendation) should happen with withContext:

suspend fun blockingSuspendFunction() = withContext(Dispatchers.Default) {
    BigInteger.probablePrime(2048, Random())
}
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