英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论