Created
November 18, 2025 06:05
-
-
Save aroranubhav/ce097b92dc5f7c32602f125495c04f8a to your computer and use it in GitHub Desktop.
Running Asynchronous Tasks in Android Using Coroutines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| 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" | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ┌───────────────────────────────┐ | |
| │ 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) │ | |
| └──────────────────────────────────────────────────┘ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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