CoroutineScope.async与CoroutineScope.launch的区别在于,async方式返回Deferred,可以获取协程的执行结果。
3.5 coroutineScope
在其他协程或挂起函数内,可通过coroutineScope来创建一个CoroutineScope,并且会立即执行coroutineScope{}内新建的协程,如下所示:
GlobalScope.launch {
Log.d(“CoroutineTag”, “GlobalScope”)
coroutineScope {
// 协程内的this即CoroutineScope
Log.d(“CoroutineTag”, “coroutineScope”)
}
}
coroutineScope是一个挂起挂起函数,所以只能在协程或挂起函数内调用:
public suspend fun coroutineScope(block: suspend CoroutineScope.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return suspendCoroutineUninterceptedOrReturn { uCont ->
val coroutine = ScopeCoroutine(uCont.context, uCont)
coroutine.startUndispatchedOrReturn(coroutine, block)
}
}
3.6 runBlocking
在线程、协程、挂起函数内,可通过runBlocking创建一个CoroutineScope,并且会立即执行runBlocking{}内新建的协程,如下所示:
GlobalScope.launch {
Log.d(“CoroutineTag”, “GlobalScope”)
runBlocking {
// 协程内的this即CoroutineScope
Log.d(“CoroutineTag”, “coroutineScope”)
}
}
与coroutineScope不同的是,runBlocking会阻塞当前线程;runBlocking是一个普通方法,所以runBlocking可以在线程中调用:
/**
- @param block 挂起函数,返回结果T就是协程的返回结果
*/
public fun runBlocking(context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
val currentThread = Thread.currentThread()
val contextInterceptor = context[ContinuationInterceptor]
val eventLoop: EventLoop?
val newContext: CoroutineContext
if (contextInterceptor == null) {
// create or use private event loop if no dispatcher is specified
eventLoop = ThreadLocalEventLoop.eventLoop
newContext = GlobalScope.newCoroutineContext(context + eventLoop)
} else {
// See if context’s interceptor is an event loop that we shall use (to support TestContext)
// or take an existing thread-local event loop if present to avoid blocking it (but don’t create one)
eventLoop = (contextInterceptor as? EventLoop)?.takeIf { it.shouldBeProcessedFromContext() }
?: ThreadLocalEventLoop.currentOrNull()
newContext = GlobalScope.newCoroutineContext(context)
}
val coroutine = BlockingCoroutine(newContext, currentThread, eventLoop)
coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
return coroutine.joinBlocking()
}
3.7 MVVM的CoroutineScope
对于MVVM架构,KTX提供了LifecycleOwner、LiveData、ViewModel对应的CoroutineScope;使用方法如下:
(1)添加依赖
dependencies {
// ViewModelScope
implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0”
// LifecycleScope
implementation “androidx.lifecycle:lifecycle-runtime-ktx:2.2.0”
// liveData
implementation “androidx.lifecyc