【发布时间】:2021-12-29 03:37:17
【问题描述】:
我已经熟悉了协程的 ContinuationInterceptor 部分
我写了下面这段代码来验证我的想法
class MyContext: CoroutineContext.Element{
override val key : CoroutineContext.Key<*>
get() = object : CoroutineContext.Key<MyContext>{}
}
val myInterceptor = object : ContinuationInterceptor {
//Key is set to a non-interceptor type
override val key : CoroutineContext.Key<MyContext>
get() = object : CoroutineContext.Key<MyContext>{}
override fun <T> interceptContinuation(continuation:
Continuation<T>): Continuation<T> {
Log.i(TAG,"interceptor:"+continuation.context[CoroutineName].toString())
return Continuation(EmptyCoroutineContext) {
thread(name = "myThread") {
continuation.resumeWith(it)
}
}
}
}
lifecycleScope.launch(myInterceptor + CoroutineName("MY1")) {
Log.i(TAG,"MY1 start:"+Thread.currentThread().name)
fun1()
launch(CoroutineName("MY2")) {
Log.i(TAG,"MY2 run:"+Thread.currentThread().name)
}
withContext(Dispatchers.Main+CoroutineName("MY3")) {
Log.i(TAG,"MY3 run:"+Thread.currentThread().name)
}
Log.i(TAG,"MY1 end:"+Thread.currentThread().name)
}
我没有将 myInterceptor Key 指定为 ContinuationInterceptor.Key。
所以协程不应该将其识别为拦截器。
MY1 和MY2 证明了这个想法,但是MY3 被myInterceptor 拦截并在新线程中运行。
我想知道:
-
为什么
myInterceptor被识别为拦截器 -
为什么
Dispatcher.Main不起作用
【问题讨论】:
标签: android kotlin kotlin-coroutines