8.5.3 Coroutines with Networking Calls

Coroutines with Networking Calls

All Kotlin coroutines run on dispatchers, and there are three types: Main, IO, and Default. It is perfectly okay to run suspending function on the main thread as long as the functions do not take a long time. Generally, networking and file IOs calls are ran on the IO thread to prevent consuming all the resources on the main thread.
Here are the general guidelines for which dispatcher to use:
Dispatcher Type
  • updating states
  • callings suspend and UI related functions
  • making networking requests
  • reading and writing to a file or database
  • CPU intensive operations like parsing JSON or sorting a list
Here's an example of how to make a networking call with coroutines:
// Dispatchers.Main
suspend fun functionA() {
val result = get("developer.android.com")
suspend fun get(url: String) =
// Dispatchers.IO
withContext(Dispatchers.IO) { actualNetworkingCall() }
As we see in the example, the main function functionA() runs on the main thread, but the actual networking call occurs on the IO thread. This allows the outer function to complete other tasks as it waits for the networking call to complete itself.
Example code blocks adapted from https://kotlinlang.org/.