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

220
Vistas
Get value from withTimeout

I'm running a coroutine that is reading from a receiverChannel. I've got this coroutine wrapped within a timeout and I want to get the number of messages it managed to read before the timeout cancels it. Here's what I have:

runBlocking {    
    val receivedMessages = withTimeoutOrNull(someTimeout) {
        var found = 0
        while (isActive && found < expectedAmount){
            val message = incomming.receive()
            // some filtering
            found++
        }
        found
    } ?: 0 // <- to not have null...

    // Currently prints 0, but I want the messages it managed to read
    println("I've received $receivedMessages messages") 
}

I know I can use atomicInteger, but I would like to keep away from java specifics here

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Local variables in a coroutine don't need to be atomic because of the happens-before guarantee even though there may be some thread swapping going on. Your code doesn't have any parallelism, so you can use the following:

runBlocking {    
    var receivedMessages = 0
    withTimeoutOrNull(someTimeout) {
        while (isActive && receivedMessages < expectedAmount){
            val message = incomming.receive()
            // some filtering
            receivedMessages++
        }
    }

    println("I've received $receivedMessages messages") 
}

If you do have multiple children coroutines running in parallel, you can use a Mutex. More info here

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