我是Kotlin / Coroutines的新手,我注意到两种不同的方式来使用CoroutineScope
。
在任何功能中,选项1如下:
CoroutineScope(Dispatchers.Default).launch {
expensiveOperation()
}
选项2是在你的类中实现CoroutineScope
接口,覆盖CoroutineContext
,然后你可以使用launch
或async
轻松启动协同程序:
@Service
class ServiceImpl() : CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + Job()
fun someFunction() {
launch {
expensiveOperation()
}
}
}
我目前正在开发一个后端端点,它将执行以下操作:
两个用例有什么区别,对于这个场景,哪个是获得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.3
的Kotlin
版本。
如果您对如何最好地构建此服务类有任何想法/建议,请告诉我。谢谢
我建议选项2.它将让你有机会为你的所有协同程序清楚地定义父Job
。这也有机会正确关闭整个执行。
还有几个coroutine上下文键包括 - CoroutineName
,CoroutineExceptionHandler
等。
最后,如果您明确传递CoroutineScope
和关联的Job,结构并发可能会更好。
https://medium.com/@elizarov/structured-concurrency-722d765aa952
另外,看看罗马的形式的解释:https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055