I've been getting familiar with the ContinuationInterceptor section of coroutines
I wrote the following section of code to verify my idea
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)
}
I don't have the myInterceptor Key specified as ContinuationInterceptor.Key.
So coroutines should not recognize it as an Interceptor.
MY1 and MY2 prove this idea, but MY3 is intercepted by myInterceptor and runs in a new thread.
I wonder:
Why is
myInterceptorrecognized as an interceptorWhy does not
Dispatcher.Mainwork
