Search code examples
androidkotlinkotlin-coroutinescoroutinecoroutinescope

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


Solution

  • 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.