Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
Thread of Dispatchers.IO coroutine

I'm learning coroutines in Android. I have the following code:

private val scope = CoroutineScope(Dispatchers.Main + job)

operator fun invoke(token: String, callback: TaskCallback) {
    scope.launch {
        withContext(Dispatchers.IO) { userDataSource.saveApiToken(token) }
        callback.onCompleted()
    }
}

I expected that userDataSource.saveApiToken(token) will be called from separate thread, but it runs on the main thread (Looper.myLooper() == Looper.getMainLooper() returns true inside the method). What can be the cause? [my mistake]

I'm using Kotlin plugin version: 1.3.11-release-Studio3.2-1 and the following dependencies: kotlinx-coroutines-core:1.0.1 and kotlinx-coroutines-android:1.0.1

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The thread in the withContext(Dispatchers.IO) block should be background thread. If we put logs there:

operator fun invoke(token: String, callback: TaskCallback) {
    scope.launch {
        withContext(Dispatchers.IO) { Log.e("Log", "t: ${Thread.currentThread()}") }
        callback.onCompleted()
    }
}

we will see Thread[DefaultDispatcher-worker-1,5,main]. So the thread is a background thread. As @Marko Topolnik mentioned in the comments, the main purpose of coroutines is to get rid of callbacks. Please try to refactor your code and remove callback: TaskCallback.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda