https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

Rohan Maity

12/28/2018, 3:45 AM
Couroutines lets you do the asynchronous work in Non Blocking thread way I used three launch{} with delay (200) in UI thread Only . So Can I say it's like Time division in UI thread . Like when first launch {} is delay(200) , then UI thread becomes Idle and second launch {} begins to execute then . Please correct me if wrong ?
g

gildor

12/28/2018, 5:37 AM
Could you show code, do you mean you have delay inside of your coroutine or between launch runs?
r

Rohan Maity

12/28/2018, 5:41 AM
Inside launch{} Coroutine
g

gildor

12/28/2018, 5:48 AM
in all this cases delay is not blocking, so all launch will start and finish almost at the same time.
delay for Main dispatcher implemented on top of non-blocking delay, so this delay doesn’t block any thread
You can easily check it yourself: https://pl.kotl.in/BJN3KNX-V
So returning to your question, there is some scheduling on thread (what you call “time division”), but there is no thread blocking, so each launch run in parallel, because no blocking operations involved
r

Rohan Maity

12/28/2018, 6:04 AM
Yeah I got that no blocking is involved But is the flow of operations is like this 1)Delay() is also suspending function. So it suspends. Make the thread in idle state. 2) Now thread is in idle state second launch{} will run ?
g

gildor

12/28/2018, 6:11 AM
Make the thread in idle state
It’s wrong
No threading involved in this case.
For example in case of delay() implementation for Android Main dispatcher will be started new Handler with delay, this managed by message queue of handler, so no thread switching, no thread idle. coroutine just subscribed on callback and return from suspend state when callback will be called
r

Rohan Maity

12/28/2018, 6:15 AM
Ok So under the hood only CallBack is involved in MY CASE . But still all the tasks happen parallel .?
g

gildor

12/28/2018, 6:19 AM
Because
delay
does nothing, so delay operation started and event queue just spin it until delay finished. If you intereseted how it implemented, check Android Looper implementation or
runBlocking
event queue in kotlinx.coroutines, it’s universal approach, used a lot for async operations on single-threaded environment, for example in JS
r

Rohan Maity

12/28/2018, 9:22 AM
Great 😀 . I just knew from the surface the working of looper . I will check deeply then