start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred {
val newContext = newCoroutineContext(context)
val coroutine = if (start.isLazy)
LazyDeferredCoroutine(newContext, block) else
DeferredCoroutine(newContext, active = true)
coroutine.start(start, coroutine, block)
return coroutine
}
可以看出,async
与launch
一样,也会新创建一个新的协程,不同的是launch
返回的是Job
类型,而async
返回的是Deferred
类型(Deferred是Job的子类)。我们通过个小例子来看下async
如何使用,如下:
coroutineScope.launch(Dispatchers.IO) {
val a = async{ getUserInfo() }
// 执行协程
val userInfo = a.await()
}
上述代码中val a = async{ getUserInfo() }
并没有真正去执行getUserInfo()
,只是返回了一个名为a的Deferred
型对象。a.await()
才是真正开始去执行协程,使得getUserInfo()
得到执行,返回userInfo
(**await()返回的数据类型取决于async{}**最后一行代码返回的类型)。所以可以得出结论,async
只是创建,await
才是执行。另外,async
同样可以指定运行线程:
val a = async(Dispatchers.IO){ g