正确的方法实现withContext,但不在Kotlin中引入协同路由作用域/作业
下面的正确的方法实现withContext,但不在Kotlin中引入协同路由作用域/作业,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,下面的withContext实现是否有效,以调用带有扩展coroutineContext的块 suspend fun <T, R> withContext(context: CoroutineContext, receiver: T, block: suspend T.() -> R): R { val newCoroutineContext = coroutineContext + context return suspendCoroutine { cont
withContext
实现是否有效,以调用带有扩展coroutineContext
的块
suspend fun <T, R> withContext(context: CoroutineContext, receiver: T, block: suspend T.() -> R): R {
val newCoroutineContext = coroutineContext + context
return suspendCoroutine { cont ->
block.startCoroutine(receiver, Continuation(newCoroutineContext) { cont.resumeWith(it) })
}
}
fun projectActionBuilder(block: suspend ActionScope<Project>.() -> Unit): Action = actionBuilder {
disableWith { e ->
e.presentation.isEnabled = false
e.presentation.isVisible = e.project != null
}
val project = disableIfNullProject()
val receiver = object : ActionScope<Project>, ActionControlScope by this {
override val receiver: Project get() = project
override suspend fun execute(block: () -> Unit) = this@actionBuilder.execute { block() }
}
withContext(ProjectElement(project), receiver, block)
}
fun actionBuilder(block: suspend ActionScope<Any>.() -> Unit): Action = object : Action {
override fun update(e: AnActionEvent) {
var disableBlock = defaultDisableBlock
block.startCoroutine(object : ActionScope<Any> {
override val event: AnActionEvent get() = e
override val receiver: Any get() = "nothing"
override suspend fun disable(block: ((AnActionEvent) -> Unit)?): Nothing { (block ?: disableBlock)(e); suspendCoroutine<Nothing> { } }
override fun disableWith(block: (AnActionEvent) -> Unit) { disableBlock = block }
override suspend fun execute(block: () -> Unit) { e.presentation.isEnabledAndVisible = true }
}, nop)
}
override fun actionPerformed(e: AnActionEvent) {
block.startCoroutine(object : ActionScope<Any> {
override val event: AnActionEvent get() = e
override val receiver: Any get() = "nothing"
override suspend fun disable(block: ((AnActionEvent) -> Unit)?): Nothing = suspendCoroutine { }
override fun disableWith(block: (AnActionEvent) -> Unit) { }
override suspend fun execute(block: () -> Unit): Unit = block()
}, nop)
}
}
suspend fun ActionScope<Any>.executeScope(block: suspend CoroutineScope.() -> Unit) = coroutineContext.let {
execute {
(GlobalScope + it).launch(allowCancelAndLogErrorsHandler + AppDispatcher.immediate) { block() }
}
}