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

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

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