Home > OS >  kotlin coroutine wait in while loop
kotlin coroutine wait in while loop

Time:04-27

I have a infinite loop

runBlocking(
        context = Dispatchers.IO
    ) {
        while (true) {
            launch(
                context = exceptionHandler
            ) {
                println("time reached")
                delay(
                    timeMillis = 3_600_000
                )
            }
        }
    }

I expect that while print "time reached" every one hour.

but when I run the program, console prints "time reached" infinitely!

how can I fix that

CodePudding user response:

You can fix it by moving while loop into the coroutine builder:

runBlocking(context = Dispatchers.IO) {
    launch(context = exceptionHandler) {
         while (true) {
             println("time reached")
             delay(timeMillis = 3_600_000)
         }
    }
}
  • Related