Kotlin – 如何向父`coroutineScope`协程添加名称?

huangapple go评论60阅读模式
英文:

Kotlin - how to add name to parent `coroutineScope` coroutine?

问题

It's clear to me that I can name the coroutines when using launch:

launch(CoroutineName("test")) { ... }

However, I am struggling to get rid of anonymous coroutines showing up on debugger when the current job is a coroutineScope:

suspend fun test = coroutineScope { ... }

What's the easiest way to add a name to coroutineScope? Currently, it's seen as:

job = "coroutine#1":ScopeCoroutine{Active}@5bf76be8

英文:

It's clear to me that I can name the coroutines when using launch:

launch(CoroutineName("test")) { ... }

However, I am struggling to get rid of anonymous coroutines showing up on debugger, when the current job is a coroutineScope.

suspend fun test = coroutineScope { ... }

what's the easiest way to add a name to coroutineScope? Currently it's seen as:

job = "coroutine#1":ScopeCoroutine{Active}@5bf76be8

答案1

得分: 1

我发现关键是使用 withContext 包装。

我制作了一个实用程序来执行这个操作:

suspend fun <R> coroutineScopeNamed(name: String? = null, block: suspend CoroutineScope.() -> R) =
    withContext(name?.let { CoroutineName(name) } ?: coroutineContext) {
        coroutineScope(block)
    }

job = "name#1":ScopeCoroutine{Active}@16e7de7d

另一个选项是使类实现 CoroutineScope 并添加

override val coroutineContext: CoroutineContext = 
  context + CoroutineName("<name>")

然而,这并不满足我,因为它在类级别而不是函数级别添加了名称。

还要注意的一点是,在添加 CoroutineName 时不保留父名称,因此新名称本身应包含所有所需的上下文信息。

英文:

I found that the trick is to wrap with withContext.

I made a utility to do that:

suspend fun <R> coroutineScopeNamed(name: String? = null, block: suspend CoroutineScope.() -> R) =
    withContext(name?.let { CoroutineName(name) } ?: coroutineContext) {
        coroutineScope(block)
    }

job = "name#1":ScopeCoroutine{Active}@16e7de7d

Another option is to make the class implement CoroutineScope and add

override val coroutineContext: CoroutineContext = 
  context + CoroutineName("<name>")

however, that doesn't satisfy me because it adds a name on class-level and not on function-level

Another thing to note is that parent names are not kept when adding CoroutineName, so the new name should contain all context information needed itself.

huangapple
  • 本文由 发表于 2023年3月15日 20:16:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定