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

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

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