Junior — Middle
How does the completion of asynchronous operations or requests occur?
sobes.tech AI
Answer from AI
Completion of asynchronous operations in Android usually occurs through callback methods, Future/Promise, or coroutines (Kotlin). For example, when using AsyncTask, the result is returned in the onPostExecute() method. In modern applications, coroutines are more commonly used, where the completion of an operation is handled after a suspend function, or through Flow or LiveData, which notify about changes.
Example with coroutines:
GlobalScope.launch {
val result = asyncOperation() // suspend function
withContext(Dispatchers.Main) {
// Handling the result on the main thread
updateUI(result)
}
}
Callback interfaces are also frequently used, where a method is called upon completion of an operation, or RxJava, where a subscriber receives a completion event.