Sobes.tech
Junior — Middle

How to return to the main UI thread after performing a background operation?

sobes.tech AI

Answer from AI

In Android, to return to the main (UI) thread after performing a background operation, classes like Handler, runOnUiThread(), or modern tools such as LiveData, ViewModel, and Coroutine with the Dispatchers.Main dispatcher are usually used.

Example using runOnUiThread():

new Thread(() -> {
    // Background operation
    String result = doBackgroundWork();

    // Return to UI thread
    runOnUiThread(() -> {
        // Update UI
        textView.setText(result);
    });
}).start();

Example with Kotlin Coroutines:

GlobalScope.launch(Dispatchers.IO) {
    val result = doBackgroundWork()
    withContext(Dispatchers.Main) {
        textView.text = result
    }
}