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
Answer
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
.
Related Questions
- → should I choose reactjs+f7 or f7+vue.js?
- → Phonegap Android write to sd card
- → Local reference jquery script in nanohttpd (Android)
- → Click to navigate on mobile devices
- → How to allow api access to android or ios app only(laravel)?
- → Access the Camera and CameraRoll on Android using React Native?
- → React native change listening port
- → What is the default unit of style in React Native?
- → Google play market autocomplete icon
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → Using Laravel with Genymotion
- → react native using like web-based ajax function
- → react native pdf View