Hi guys, can someone explain what is behind of the...
# coroutines
s
Hi guys, can someone explain what is behind of the
delay
? I want to know because when a launch a new job in Dispatchers.Main and use Thread.sleep, the codes blocks, and its okay, this make sense, but, how
delay
doesn't block when I use it in the Dispatchers.Main? He create a new single thread pool and waits three and use suspendCoroutine and resume after that?
d
iirc,
Dispatchers.Main
has support for delays without having to create a new thread pool. It basically depends on where you use
delay
.
So in the case of android, I'm guessing
Handler.postDelayed
is used.
s
Now I see, this is why when a use delay and the screen goes off (deep sleep) the code after "never" runs
d
Wake locks to the rescue.
l
Or
AlarmManager
depending on your use case
a
Or
WorkManager
. There are startlingly few reasons for using
AlarmManager
in 2019.
l
Needing exact time is one good reason, right?
a
The use cases for needing an exact time are very slim, basically if you are an alarm clock or related reminder app. The only AlarmManager APIs that actually grant exact time wakeup anymore are the ones that show pending alarm iconography in the status bar and system UI
All others fuzz and coalesce alarms sent to apps because it scales badly for system and network health otherwise
s
Tkx everyone for the help, I pick AlarmManager because the application that I am working on is embeded. But the AlarmManager is kinda hard to work and use it just for a throttling is kinda annoying. I build a lib using
suspendCoroutine
that's delay using AlarmManager: https://github.com/DevSrSouza/coroutines-alarm-delay#coroutines-alarm-delay
l
You could use
suspendCancellableCoroutine
and cancel the pending intent in the finally block.