Kotlin Coroutines - 使用Coroutine Scope / Context的不同选项?

问题描述 投票:0回答:1

我是Kotlin / Coroutines的新手,我注意到两种不同的方式来使用CoroutineScope

在任何功能中,选项1如下:

CoroutineScope(Dispatchers.Default).launch { 
    expensiveOperation() 
}

选项2是在你的类中实现CoroutineScope接口,覆盖CoroutineContext,然后你可以使用launchasync轻松启动协同程序:

@Service
class ServiceImpl() : CoroutineScope {

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Default + Job()

    fun someFunction() {
        launch {
            expensiveOperation()
        }
    }
}

我目前正在开发一个后端端点,它将执行以下操作:

  1. 接受请求
  2. 将请求上下文保存到数据库
  3. 在后台启动一个非阻塞协程,对请求执行昂贵/冗长的操作,并立即返回一个http 200.(基本上,一旦我们保存了上下文,我们就可以返回响应并让请求进程在后台)

两个用例有什么区别,对于这个场景,哪个是获得CoroutineScope的首选方法?

该端点可能每秒接收多个请求,并且冗长的操作将花费一两分钟,因此肯定会有多个请求同时处理,源自各种请求。

另外,如果它是选项2,我是否要将范围/上下文传递给执行繁重处理的函数?或者这是不必要的?例如:

class ServiceImpl():CoroutineScope {

override val coroutineContext: CoroutineContext
    get() = Dispatchers.Default + Job()

fun someFunction() {
    launch {
        expensiveOperation(CoroutineScope(coroutineContext))
    }
}

private fun expensiveOperation(scope: CoroutineScope) 
    {
        // perform expensive operation
    }

}

这是一个Spring Boot应用程序,我正在使用1.3Kotlin版本。

如果您对如何最好地构建此服务类有任何想法/建议,请告诉我。谢谢

kotlin kotlin-coroutines
1个回答
0
投票

我建议选项2.它将让你有机会为你的所有协同程序清楚地定义父Job。这也有机会正确关闭整个执行。

还有几个coroutine上下文键包括 - CoroutineNameCoroutineExceptionHandler等。

最后,如果您明确传递CoroutineScope和关联的Job,结构并发可能会更好。 https://medium.com/@elizarov/structured-concurrency-722d765aa952

另外,看看罗马的形式的解释:https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055

© www.soinside.com 2019 - 2024. All rights reserved.