Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of a coroutine in Kotlin?

I'm curious about the internal working of a coroutine when suspended on the main thread. The real question is how to log a suspended function which is a coroutine on the main thread. Where exactly the execution is taking place? Is it a virtual thread?

like image 400
Sharan Avatar asked Sep 05 '25 00:09

Sharan


2 Answers

If you are talking about logging the coroutine name:

You can achieve this by

  1. Give name to coroutine(if you want custom name): launch(CoroutineName("My-Coroutine"))

  2. Enable the logging in IntelliJ toolbar menu: Run -> Edit Configuration and add

-Dkotlinx.coroutines.debug in VM options.

VM Option in Edit Configuration

Then you can see @My-Coroutine in logcat.

Try below code after Edit Configuration change:

fun main() = runBlocking {
println("   'runBlocking': I'm working in thread ${Thread.currentThread().name}")

val job = launch(CoroutineName("my-custom-name")) {
    println("   'runBlocking': I'm working in thread ${Thread.currentThread().name}")

}

job.join()}

Result: Result

like image 109
aman.nepid Avatar answered Sep 07 '25 13:09

aman.nepid


The other answers don't answer the question directly "How to get the name of a coroutine in Kotlin?"; instead, they suggest how to name a coroutine.

If inside a coroutine, the name can be retrieved using currentCoroutineContext()[CoroutineName].

If outside a coroutine, there's no direct way to retrieve the name using a reference to a Job or Deferred (too bad). However, there's a reflection hack that can be used. Of course, the usual warnings come attached, which are, no type safety and hacking into internal APIs that may change anytime.

@Suppress("UNCHECKED_CAST")
val nameString = AbstractCoroutine::class.memberFunctions
    .single { it.name == "nameString" } as Function1<AbstractCoroutine<*>, String>
val name = nameString(job as AbstractCoroutine<*>)
    .replace("\"", "")
    .takeWhile { it != '#' }

The method/function containing this code has to be marked with @InternalCoroutinesApi.

like image 30
Abhijit Sarkar Avatar answered Sep 07 '25 14:09

Abhijit Sarkar