Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!