在 Kotlin 中创建子协程作用域

Create a child coroutine scope in Kotlin

短篇(-ish)

我想知道是否有或多或少的标准方法来创建协程 context/scope 这样:

coroutineScope() does exactly what I need, it creates a child scope, but it does not simply return it to the caller - we need to pass a lambda and coroutine lifetime is limited to the execution of this lambda. On the other hand, CoroutineScope() 工厂创建一个 long-运行ning 作用域,我可以存储它供以后使用,但它与当前协程无关。

我能够通过以下方式手动创建这样的范围:

suspend fun createChildCoroutineScope(): CoroutineScope {
    val ctx = coroutineContext
    return CoroutineScope(ctx + Job(ctx.job))
}

乍一看,它似乎完全符合我的需要。它是否等同于 coroutineScope() 所做的,或者我的解决方案可能不完整,我应该执行一些额外的任务?我试着阅读coroutineScope()的源代码,但它相当复杂。有没有更简单或更标准的方法来创建子作用域?

此外,它是否被视为不良做法或反模式?我只是担心,如果还没有这样一个简单的函数,那么可能是有原因的,我不应该这样使用协程。

用例(更长的故事)

通常,当我实现某种可以异步安排后台操作的长期 运行ning 服务时,我发现需要这样做:

class MyService {
    fun scheduleSomeTask() {
        // start task in the background
        // return immediately
    }
}

使用协程有几种可能性:

  1. GlobalScope,但是不好.

  2. 使用当前协程使 scheduleSomeTask() 可暂停和 运行 后台任务。在很多情况下,我认为这种方法并不是真正合适的方法:

    • 后台任务由调用者“拥有”,而不是由服务本身“拥有”。如果我们例如停止服务,后台任务仍会运行ning.
    • 要求调度功能是可挂起的。我认为这是错误的,因为我真的不明白为什么某些 Java 代码或协程上下文之外的代码不应该被允许在我的服务中安排任务。
  3. 给我的服务一个定义的生命周期,在 stopping/destroying 时使用 CoroutineScope()cancel() 创建范围。这很好,但我认为我们仍然可以从协程的结构化并发中受益,所以对我来说,我的服务是分离的是一个缺点。

    例如,我们有一个文件下载服务,它由(拥有)其他服务组成,包括数据缓存服务。使用 start()/stop() 服务的典型方法,我们需要手动控制生命周期,并且很难正确处理故障。协程使它变得更容易:如果缓存服务崩溃,它会自动传播到下载服务;如果下载服务需要停止,它只是取消它的协程,并且可以确保它不会泄漏它的任何子组件。所以对我来说,在设计由几个小服务组成的应用程序时,协程的结构化并发可能非常有用。

我目前的做法是这样的:

class MyService {
    private lateinit var coroutine : CoroutineScope

    suspend fun start() {
        coroutine = createChildCoroutineScope() + CoroutineName("MyService")
    }

    fun stop() {
        coroutine.cancel()
    }

    fun scheduleSomeTask() {
        coroutine.launch {
            // do something
        }
    }
}

或者,或者:

class MyService(
    private val coroutine: CoroutineScope
) {
    companion object {
        suspend fun start() = MyService(createChildCoroutineScope())
    }
}

这样服务就可以“拦截”启动它的协程并将其后台操作附加到它。但正如我所说,我不确定这是否出于某种原因不被视为反模式。

另外,我知道我的 createChildCoroutineScope() 有潜在的危险。通过调用它,我们使当前协程无法完成。这可能是库中不存在此类函数的原因。另一方面,它与做类似的事情并没有什么不同:

launch {
    while (true) {
        socket.accept() // assume it is suspendable, not blocking
        // launch connection handler
    }
} 

事实上,从技术角度来看,这两种方法非常相似。它们具有相似的并发结构,但我相信“我的”方法通常更简洁、更强大。

我找到了一个非常好的答案和对我的问题的解释。 Roman Elizarov 在他的一篇文章中准确地讨论了我的问题:https://elizarov.medium.com/coroutine-context-and-scope-c8b255d59055

他解释说,虽然技术上可以“捕获”挂起函数的当前上下文并使用它来启动后台协程,但强烈建议不要这样做:

Do not do this! It makes the scope in which the coroutine is launched opaque and implicit, capturing some outer Job to launch a new coroutine without explicitly announcing it in the function signature. A coroutine is a piece of work that is concurrent with the rest of your code and its launch has to be explicit.

If you need to launch a coroutine that keeps running after your function returns, then make your function an extension of CoroutineScope or pass scope: CoroutineScope as parameter to make your intent clear in your function signature. Do not make these functions suspending.

我知道我可以将 CoroutineScope/CoroutineContext 传递给一个函数,但我认为挂起函数是一种更短、更优雅的方法。然而,上面的解释让地狱变得很有意义。如果我们的函数需要获取调用者的协程 scope/context,请明确说明这一点 - 它再简单不过了。

这也与“热”/“冷”执行的概念有关。挂起函数的一大优点是它们允许我们轻松创建 long-运行 任务的“冷”实现。虽然我相信在协程文档中没有明确指定挂起函数应该是“冷的”,但满足这个要求通常是个好主意,因为我们的挂起函数的调用者可能会认为它是“冷的”。捕获协程上下文会使我们的函数变得“热”,因此应该通知调用者。