As per the documentation, we can name coroutine using CoroutineName("theName")
If I run it without the name (in the unit-test)
runBlocking {
launch {
println("main runBlocking pre : ${Thread.currentThread().name}:${coroutineContext[Job]}")
delay(500)
println("main runBlocking post : ${Thread.currentThread().name}:${coroutineContext[Job]}")
}
Both the Thread.currentThread().name
and coroutineContext[Job]
will assign an ID to the coroutine name, hence the print out as below (notice coroutine#2
)
main runBlocking pre : main @coroutine#2:"coroutine#2":StandaloneCoroutine{Active}@39529185
main runBlocking post : main @coroutine#2:"coroutine#2":StandaloneCoroutine{Active}@39529185
If I run it with the name (in the unit-test)
runBlocking {
launch(CoroutineName("CustomName")) {
println("main runBlocking pre : ${Thread.currentThread().name}:${coroutineContext[Job]}")
delay(500)
println("main runBlocking post : ${Thread.currentThread().name}:${coroutineContext[Job]}")
}
It will print (notice the @CustomName#2
)
main runBlocking pre : main @CustomName#2:"CustomName#2":StandaloneCoroutine{Active}@78e117e3
main runBlocking post : main @CustomName#2:"CustomName#2":StandaloneCoroutine{Active}@78e117e3
However, if I run it in Android as below
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]}")
}
}
}
It prints
Track: main runBlocking pre : main:StandaloneCoroutine{Active}@5e322c2
Track: main runBlocking post : main:StandaloneCoroutine{Active}@5e322c2
The coroutine name is not given, nor is the coroutine assigned ID. I can only identify from the address ID i.e. @5e322c2
, which is not guaranteed to be the same always.
How can I assign the coroutine name in Android?
The coroutine name is only used in debugging mode. However, you can enable in your application:
System.setProperty("kotlinx.coroutines.debug", "on" )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With