Junior — Middle
What methods can you use to implement asynchronous task execution in an application?
sobes.tech AI
Answer from AI
For asynchronous task execution in Android, several approaches can be used:
- AsyncTask (deprecated but still encountered sometimes)
- Handler and HandlerThread for managing threads and message queues
- Thread / Runnable — creating and starting new threads manually
- ExecutorService — thread pool for managing tasks
- Coroutines (Kotlin) — modern and convenient way of asynchronous programming
- RxJava — reactive programming with support for asynchrony
Example using Kotlin Coroutines:
import kotlinx.coroutines.*
fun fetchData() {
GlobalScope.launch(Dispatchers.IO) {
val data = networkRequest() // runs in background thread
withContext(Dispatchers.Main) {
updateUI(data) // updates UI on main thread
}
}
}