Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda