Sobes.tech
Middle

What asynchronous primitives do you use for data processing in Android applications?

sobes.tech AI

Answer from AI

  • AsyncTask (deprecated, not recommended for use)
  • Handler and Looper
  • Threads (Thread) using ExecutorService and ThreadPoolExecutor
  • Kotlin Coroutines
  • ReactiveX (RxJava/RxKotlin)
// Example of using Kotlin Coroutines
suspend fun loadData(): String {
    delay(1000) // Simulate a long operation
    return "Data loaded"
}

fun fetchData() {
    // Launch coroutine on the main thread (to update UI after loading)
    lifecycleScope.launch {
        val data = withContext(Dispatchers.IO) {
            // Switch to IO thread for network request
            loadData()
        }
        // Update UI
        textView.text = data
    }
}
// Example of using ExecutorService
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());

executor.execute(() -> {
    // Perform background task
    String result = fetchDataInBackground();

    handler.post(() -> {
        // Update UI on the main thread
        textView.setText(result);
    });
});

Comparison table of some primitives:

Primitive Level of abstraction Approach Cancellation convenience Testing convenience
Handler/Looper Low Callbacks Medium Medium
ExecutorService Medium Callbacks/Future Medium Medium
Coroutines High Structured High High
RxJava/RxKotlin High Reactive High High
What asynchronous primitives do you use for data… - sobes.tech