Junior — Middle
What happens if a network request is executed in the main thread of the program?
sobes.tech AI
Answer from AI
Performing a network request on the main (UI) thread of an Android application will lead to blocking the user interface until the request completes. As a result, the application will stop responding to user actions, which can cause an ANR (Application Not Responding) — a system warning about freezing.
Therefore, network operations should be performed in a background thread, for example, using AsyncTask, Thread, Coroutine, or libraries like Retrofit that support asynchrony.
Example with Kotlin Coroutine:
GlobalScope.launch(Dispatchers.Main) {
val result = withContext(Dispatchers.IO) {
// network request
}
// update UI with the result
}