Skip to content

Instantly share code, notes, and snippets.

@aroranubhav
Created November 18, 2025 06:05
Show Gist options
  • Select an option

  • Save aroranubhav/ce097b92dc5f7c32602f125495c04f8a to your computer and use it in GitHub Desktop.

Select an option

Save aroranubhav/ce097b92dc5f7c32602f125495c04f8a to your computer and use it in GitHub Desktop.
Running Asynchronous Tasks in Android Using Coroutines
/**
This example demonstrates how to perform background work in Android using Coroutines.
**/
class AsyncWithCoroutines {
private val scope = CoroutineScope(Dispatchers.Default)
companion object {
const val TAG = "AsyncWithCoroutines"
}
fun runAsyncTask() {
Log.d(TAG, "usingCoroutines: Coroutine start!")
scope.launch {
val result = runBackgroundTask()
Log.d(TAG, "usingCoroutines: $result")
}
Log.d(TAG, "usingCoroutines: Coroutine end!")
}
private suspend fun runBackgroundTask(): String {
delay(5000) // simulate background work
return "Task Completed"
}
}
┌───────────────────────────────┐
│ runAsyncTask() (MAIN) │
└───────────────────────────────┘
│ launches coroutine
┌──────────────────────────────────────────────────┐
│ scope.launch { ... } running on |
| Dispatchers.Default |
└──────────────────────────────────────────────────┘
│ suspend runBackgroundTask()
┌───────────────────────────────┐
│ delay(5000) suspends |
| coroutine |
└───────────────────────────────┘
│ After delay resumes on same dispatcher
┌───────────────────────────────┐
│ return "Task Completed" │
└───────────────────────────────┘
┌──────────────────────────────────────────────────┐
│ Coroutine resumes and logs result (Background) │
└──────────────────────────────────────────────────┘
usingCoroutines: Coroutine start!
usingCoroutines: Coroutine end!
-- 5 seconds later --
usingCoroutines: Task Completed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment