如何在Android中命名协程?

Ely*_*lye 5 android kotlin kotlin-coroutines

根据文档,我们可以使用命名协程CoroutineName("theName")

如果我在没有名称的情况下运行它(在单元测试中)

        runBlocking {
            launch { 
                println("main runBlocking pre       : ${Thread.currentThread().name}:${coroutineContext[Job]}")
                delay(500)
                println("main runBlocking post      : ${Thread.currentThread().name}:${coroutineContext[Job]}")
            }
Run Code Online (Sandbox Code Playgroud)

无论是Thread.currentThread().namecoroutineContext[Job]将分配ID的协程名称,因此打印出如下(通知coroutine#2

main runBlocking pre       : main @coroutine#2:"coroutine#2":StandaloneCoroutine{Active}@39529185
main runBlocking post      : main @coroutine#2:"coroutine#2":StandaloneCoroutine{Active}@39529185
Run Code Online (Sandbox Code Playgroud)

如果我使用名称运行它(在单元测试中)

        runBlocking {
            launch(CoroutineName("CustomName")) { 
                println("main runBlocking pre       : ${Thread.currentThread().name}:${coroutineContext[Job]}")
                delay(500)
                println("main runBlocking post      : ${Thread.currentThread().name}:${coroutineContext[Job]}")
            }
Run Code Online (Sandbox Code Playgroud)

它将打印(注意@CustomName#2

main runBlocking pre       : main @CustomName#2:"CustomName#2":StandaloneCoroutine{Active}@78e117e3
main runBlocking post      : main @CustomName#2:"CustomName#2":StandaloneCoroutine{Active}@78e117e3
Run Code Online (Sandbox Code Playgroud)

但是,如果我在 Android 中运行它,如下所示

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        runBlocking {
            launch(CoroutineName("CustomName")) { // context of the parent, main runBlocking coroutine
                Log.d("Track", "main runBlocking pre       : ${Thread.currentThread().name}:${coroutineContext[Job]}")
                delay(500)
                Log.d("Track", "main runBlocking post      : ${Thread.currentThread().name}:${coroutineContext[Job]}")
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

它打印

Track: main runBlocking pre       : main:StandaloneCoroutine{Active}@5e322c2
Track: main runBlocking post      : main:StandaloneCoroutine{Active}@5e322c2
Run Code Online (Sandbox Code Playgroud)

没有给出协程名称,也没有给出协程分配的 ID。我只能从地址 ID ie 中识别@5e322c2,不能保证始终相同。

如何在 Android 中分配协程名称?

小智 3

协程名称仅在调试模式下使用。但是,您可以在应用程序中启用:

System.setProperty("kotlinx.coroutines.debug", "on" )
Run Code Online (Sandbox Code Playgroud)