Sobes.tech
Junior — Middle

Can the main thread perform network requests without causing blocking or performance issues?

sobes.tech AI

Answer from AI

In Android, the main (UI) thread should not perform network requests directly, as this leads to interface blocking and degraded app performance. Network operations can take a significant amount of time, and if they are executed on the main thread, the app will become unresponsive to user actions.

To prevent blocking, the following are used:

  • Asynchronous tasks (AsyncTask, although now deprecated)
  • Threads (Thread, HandlerThread)
  • Libraries supporting asynchrony (e.g., Retrofit with Coroutines)
  • Kotlin Coroutines or RxJava

Example with Kotlin Coroutines:

GlobalScope.launch(Dispatchers.Main) {
    val result = withContext(Dispatchers.IO) {
        // Perform network request in background thread
        fetchDataFromNetwork()
    }
    // Update UI with the result
    updateUI(result)
}

Thus, the main thread is not blocked, and the application remains responsive.