How would you replace legacy AsyncTask usage in Android?

Instruction: Explain AsyncTask and its deprecation, then choose replacements for a screen-bound request and persistent deferred work. Discuss lifecycle, cancellation, failure, and scheduling guarantees.

Context: This question evaluates the candidate's knowledge of Android's threading and background task management. It challenges them to demonstrate an understanding of `AsyncTask`, its typical use cases, and its limitations, encouraging discussion on modern alternatives for background processing.

Updated

Example answer

AsyncTask was deprecated in Android API level 30. Recognize it in legacy code; do not choose it for new work. Its doInBackground method ran work off the UI thread, with callbacks such as onPostExecute used to deliver results. Activity references, configuration changes, cancellation, and inconsistent execution behavior made it fragile.

Choose the replacement by the task's lifetime and contract:

  • Work needed while a screen or ViewModel is alive: use lifecycle-aware Kotlin coroutines, with blocking I/O dispatched appropriately, explicit loading/error state, and cancellation propagated. For Java, an executor plus deliberate main-thread result delivery is an option.
  • Deferrable work that must survive process exit: use WorkManager with appropriate constraints, retry/backoff, and idempotent work. It schedules persistent work; it does not promise an exact start time or unconditional success. User force-stop and platform restrictions still matter.
  • A user-visible ongoing operation: evaluate the applicable foreground-service or specialized platform API requirements; long duration alone does not imply WorkManager is the right tool.

For example, loading a profile to display on the current screen is an in-process task. Uploading queued records after connectivity returns may be persistent work. During migration, test rotation, navigation away, process recreation, cancellation, and failure; ensure a completed old request cannot overwrite a newer result.

Sources

AsyncTask deprecation; Coroutines and lifecycle; Persistent work.

Related Questions