kotlin 协程基础,阿里P8架构师的Android大厂面试题总结

本文详细介绍了Kotlin协程的基础概念,包括coroutineScope、runBlocking、MVVM中的使用,以及各种协程启动方式。重点讨论了CoroutineScope.launch与CoroutineScope.async的区别,并展示了在Android开发中的应用场景,如在ViewModel和Fragment中的使用。同时,文章涵盖了CoroutineContext、CoroutineStart、Job的状态管理、挂起函数和协程调度。最后,提到了协程间的数据通信。
摘要由CSDN通过智能技术生成

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

参考:developer.android.com/topic/libra…

对于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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值