How does `delay()` behave, if it's running in the ...
# android
p
How does
delay()
behave, if it's running in the background? Can I rely, that it will be finished after correct delay?
For example:
Copy code
val scope = MainScope()
scope.launch {
    println("session start")
    delay(10.minutes)
    println("session expired")
}
When does this finish, if app is in background for like 5 minutes?
c
Depends on the device manufacturer and os and its sleep and doze settings - but most probably it will not run.
p
I did some quick tests and it looks like in worst case, this can finish in 15 minutes. I thought that the delay would finish at the correct end time.
c
As I said, depending on the device and OS your app can also be killed at any time in background and it will never complete. I.e user has battery saving enabled and so on.
Also you can never be sure the user itself kills the app through the app switcher.
p
Yeah, I understand what happens at process death. I was just wondering what would happen until then.
s
Delay will suspend the coroutine and will make it free for the other background tasks. After the delay time - it will execute again - not compulsory on the same thread but will be continued. Note :- It can only be called inside suspend functions. Also if the activity is killed - then the coroutine will also be cancelled itself.