上一張通過四種啟動(dòng)模式除嘹,我們知道只有調(diào)度器ok写半,才能執(zhí)行協(xié)程里面的代碼,
那么協(xié)程是如何調(diào)度的尉咕?
下面是CoroutineScope.launch的源碼
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
val newContext = newCoroutineContext(context)
val coroutine = if (start.isLazy)
LazyStandaloneCoroutine(newContext, block) else
StandaloneCoroutine(newContext, active = true)
coroutine.start(start, coroutine, block)
return coroutine
}
參數(shù)start已經(jīng)講過叠蝇,block: suspend CoroutineScope.() -> Unit這個(gè)是什么?
之前kotlin基礎(chǔ)部分已經(jīng)講過龙考,如果lambda表達(dá)式是函數(shù)調(diào)用的最后一個(gè)實(shí)參蟆肆,它可以放到括號(hào)外面
所以可以這樣寫
GlobalScope.launch {
println(2)
println(Thread.currentThread().name)
}
suspend 表示掛起函數(shù)(后面會(huì)講)
CoroutineScope.() -> Unit 表示用方法作為launch方法的參數(shù)表示一個(gè)不需要返回值的函數(shù)
為什么不是() -> Unit
下面的例子將展示T.() -> Unit跟() -> Unit的區(qū)別
fun <T : View> T.afterMersure(f: T.() -> Unit) {}
fun <T : View> T.afterMersure2(f: () -> Unit) {}
class Test1 {
val layout:LinearLayout?=null
fun test(){
layout?.afterMersure {
//這里面的作用域會(huì)跟LinearLayout一致
println(this)
shouldDelayChildPressedState()
}
layout?.afterMersure2 {
println(this.layout)
// shouldDelayChildPressedState()
}
}
}
到這里也就可以理解下面的代碼
suspend fun main(){
val job = GlobalScope.launch {
log(this)
launch {
log(this)
}
}
job.join()
}