halim
04/14/2019, 12:36 PMDominaezzz
04/14/2019, 12:46 PM<http://CoroutineScope.xxx|CoroutineScope.xxx>()
spawns coroutines with the given scope with run even after the function returns. suspend fun xxx()
finishes all it's work before returning.Dominaezzz
04/14/2019, 12:50 PMsuspend
function does not block the current thread. So it might block some other dedicated thread for blocking or it might rely on the OS calling resume
.Dominaezzz
04/14/2019, 12:55 PMhalim
04/14/2019, 1:59 PMDominaezzz
04/14/2019, 2:02 PMlaunch
it'll run the code in a background thread pool.halim
04/14/2019, 2:04 PMDominaezzz
04/14/2019, 2:06 PMhalim
04/14/2019, 2:11 PMsuspend sum() {
println("$Thread.currentThread().name")
(1..VAL).sum()
}
fun main() = runBlocking() {
lunch {
sum()
}
println("end")
}
the program still run sequantielly
and sum() still run in main-thread, so suspend here what deans if suspend function run in same thread of calleruli
04/14/2019, 3:18 PMtseisel
04/14/2019, 3:40 PMrunBlocking
are executed sequentially, blocking the current thread instead of suspending (hence the name). So your code is sequential and runs on the main thread only.tseisel
04/14/2019, 3:48 PMDispatchers
are context elements that you pass to launch
or async
that define the threading policy. See https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html#dispatchers-and-threads
2. Job.cancel()
and CoroutineContext.cancel()
does the same thing: cancelling the Job and their children's.
3. Dominic explained it pretty well.uli
04/14/2019, 4:29 PMlaunch(Dispatcher.Default)
to schedule to backgroundNail Khafizov
04/14/2019, 6:17 PMlaunch
If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
runblocking
by default creates context with current thread as dispatcher, so launch
by default will be in main thread in that examplehalim
04/15/2019, 9:22 AMuli
04/15/2019, 9:25 AMsuspend sum() {
println("$Thread.currentThread().name")
(1..VAL).sum()
}
fun main() = runBlocking() {
launch(Dispatchers.Default) {
sum()
}
println("end")
}
uli
04/15/2019, 9:26 AMend
might be printed before sum
is even started. If you want to wait for execution of `sum`go like this:
suspend sum() {
println("$Thread.currentThread().name")
(1..VAL).sum()
}
fun main() = runBlocking() {
withContext(Dispatchers.Default) {
sum()
}
println("end")
}
halim
04/15/2019, 9:27 AMhalim
04/15/2019, 9:28 AMhalim
04/15/2019, 9:39 AMDominaezzz
04/15/2019, 11:06 AMhalim
04/15/2019, 11:48 AMDominaezzz
04/15/2019, 12:07 PMsuspend
functions are just sugar for functions with callbacks. Any question I had about coroutines or suspending stuff, I simply restructured the question to say callback instead of suspend and I had my answer.Dominaezzz
04/15/2019, 12:08 PMhalim
04/15/2019, 12:09 PM