Reputation: 867
In the Android official coroutines guides here, there are two code examples. In the first example, a function get(url: String) called from fetchDocs() runs on Dispatchers.IO, but in the second example it runs on Dispatchers.Main - see a second comment in each example. Is it an error, or they actually run on different Dispatchers?
First example
suspend fun fetchDocs() { // Dispatchers.Main
val result = get("https://developer.android.com") // Dispatchers.IO for `get`
show(result) // Dispatchers.Main
}
suspend fun get(url: String) = withContext(Dispatchers.IO) { /* ... */ }
Second example
suspend fun fetchDocs() { // Dispatchers.Main
val result = get("developer.android.com") // Dispatchers.Main
show(result) // Dispatchers.Main
}
suspend fun get(url: String) = // Dispatchers.Main
withContext(Dispatchers.IO) { // Dispatchers.IO (main-safety block)
/* perform network IO here */ // Dispatchers.IO (main-safety block)
} // Dispatchers.Main
}
Upvotes: 0
Views: 333
Reputation: 28352
I think the intention of the author of this article was to make the first example simplified to show that we can easily switch between threads line after line. In both examples get()
is executed using Dispatchers.Main
, but it immediately jumps to Dispatchers.IO
, so it was marked as IO
for simplicity. The documentation even mentions that:
In this example, get() still runs on the main thread (...)
Anyway, I agree this may be confusing for the reader.
Upvotes: 1