Coroutines help your app do tasks like loading data from the internet without freezing the screen. They let your app wait for data quietly while still working smoothly.
0
0
Coroutines for async networking in Android Kotlin
Introduction
Loading user profile information from a server when the app starts.
Fetching weather updates in the background without stopping the app.
Downloading images or files while letting the user keep using the app.
Sending data to a server and waiting for a response without freezing the UI.
Syntax
Android Kotlin
import kotlinx.coroutines.*
fun fetchData() = CoroutineScope(Dispatchers.IO).launch {
val data = networkCall() // suspend function
withContext(Dispatchers.Main) {
updateUI(data)
}
}launch starts a new coroutine that runs in the background.
Dispatchers.IO is used for network or disk tasks to keep the main thread free.
Examples
This example fetches data on a background thread and updates the UI on the main thread.
Android Kotlin
CoroutineScope(Dispatchers.IO).launch {
val response = fetchFromServer()
withContext(Dispatchers.Main) {
showData(response)
}
}A suspend function that simulates waiting for network data.
Android Kotlin
suspend fun fetchFromServer(): String {
delay(1000) // simulate network delay
return "Server data"
}Starts on the main thread, switches to IO for fetching, then back to main to update UI.
Android Kotlin
GlobalScope.launch(Dispatchers.Main) {
val data = withContext(Dispatchers.IO) { fetchFromServer() }
textView.text = data
}Sample App
This app shows a blank screen first, then after 1.5 seconds, it displays "Hello from network!" fetched in the background without freezing the screen.
Android Kotlin
import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.widget.TextView import kotlinx.coroutines.* class MainActivity : AppCompatActivity() { private lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) textView = TextView(this) setContentView(textView) CoroutineScope(Dispatchers.IO).launch { val data = fetchDataFromNetwork() withContext(Dispatchers.Main) { textView.text = data } } } private suspend fun fetchDataFromNetwork(): String { delay(1500) // simulate network delay return "Hello from network!" } }
OutputSuccess
Important Notes
Always update UI on the main thread to avoid crashes.
Use Dispatchers.IO for network or disk operations to keep UI smooth.
Coroutines make async code look simple and easy to read.
Summary
Coroutines let your app do network tasks without freezing the screen.
Use launch with Dispatchers.IO for background work.
Switch back to Dispatchers.Main to update the UI safely.