正确的实现withContext的方法,但未在Kotlin中引入CoroutineScope / Job

时间:2020-10-28 16:52:46

标签: kotlin kotlin-coroutines

以下withContext的实现对扩展为block的{​​{1}}进行调用是否有效?

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) }) } } 中的withContext,但是在较低的级别上没有Job API,因为我无法在标准库中找到它。

由于我对拦截不感兴趣,我应该进一步使用kotlinx.coroutines吗?我不了解suspendCoroutineUninterceptedOrReturn中使用的SafeContinuation中的机械要点。那么通过suspendCoroutine对于withContext的有效实现是什么?

有关更多情况,我正在研究一个“构建器”,以从一个暂停块中实现suspendCoroutineUninterceptedOrReturn(请参见下面的AnAction),并且我想实现一个包装器,而不是确保{ {1}},并向fun actionBuilder注入自定义event.project !=null

我不想使用ProjectElement的原因是在此级别上,构建器仅用于避免coroutineContextwithContext之间的代码重复(其中{{1} }仅用于标记进入update的部分)。因此,我想仅在需要时(例如后台工作)才开始使用Job API,只需在顶部实现actionPerformed

P.S。到目前为止,代码似乎可以正常工作,并且ActionScope<T>.execute发生了错误,因为actionPerformed创建了根作业,但是由于某种原因而不是取消(不确定此时是否有问题)。 / p>

executeScope

0 个答案:

没有答案