Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

414
Views
¿Cómo obtener el nombre de una rutina en Kotlin?

Tengo curiosidad sobre el funcionamiento interno de una rutina cuando está suspended en el hilo principal. La verdadera pregunta es cómo registrar una función suspended que es una rutina en el hilo principal. ¿Dónde se lleva a cabo exactamente la ejecución? ¿Es un hilo virtual?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Si está hablando de registrar el nombre de la rutina:

Puedes lograr esto por

  1. Asigne un nombre a coroutine (si desea un nombre personalizado): launch(CoroutineName("My-Coroutine"))

  2. Habilite el inicio de sesión en el menú de la barra de herramientas de IntelliJ: Ejecutar -> Editar configuración y agregar

-Dkotlinx.coroutines.debug en opciones de VM.

Opción de VM en Editar configuración

Luego puede ver @My-Coroutine en logcat.

Pruebe el siguiente código después de editar el cambio de configuración:

 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()}

Resultado: Resultado

over 4 years ago · Santiago Trujillo Report

0

Las otras respuestas no responden directamente a la pregunta " ¿Cómo obtener el nombre de una rutina en Kotlin? "; en cambio, sugieren cómo nombrar una rutina.

Si está dentro de una rutina, el nombre se puede recuperar usando currentCoroutineContext()[CoroutineName] .

Si está fuera de una rutina, no hay una forma directa de recuperar el nombre usando una referencia a un Job o Deferred (muy mal). Sin embargo, hay un truco de reflexión que se puede usar. Por supuesto, se adjuntan las advertencias habituales, que son, ningún tipo de seguridad y piratería en las API internas que pueden cambiar en cualquier momento.

 @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 != '#' }

El método/función que contiene este código debe marcarse con @InternalCoroutinesApi .

over 4 years ago · Santiago Trujillo Report

0

Puede dar un nombre a la rutina usando CoroutineName(name:String) al momento de crear la rutina:

 repeat(5) { GlobalScope.launch(CoroutineName("$it")) { displayGreetingsFor(it) } }

Para recuperar el nombre dado a coroutine, use coroutineContext[CoroutineName.Key] como se muestra a continuación:

 private suspend fun displayGreetingsFor(i: Int) { delay(100) println( " ${coroutineContext[CoroutineName.Key]} is executing on thread : ${Thread.currentThread().name}" ) }

Esto se imprimirá siguiendo o/p en la consola:

 CoroutineName(0) is executing on thread : DefaultDispatcher-worker-3 CoroutineName(1) is executing on thread : DefaultDispatcher-worker-2 CoroutineName(2) is executing on thread : DefaultDispatcher-worker-8 CoroutineName(3) is executing on thread : DefaultDispatcher-worker-6 CoroutineName(4) is executing on thread : DefaultDispatcher-worker-5
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!