import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.TextView
import kotlinx.coroutines.*
class ThreadSwitchActivity : AppCompatActivity() {
private lateinit var messageTextView: TextView
private lateinit var fetchButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_thread_switch)
messageTextView = findViewById(R.id.messageTextView)
fetchButton = findViewById(R.id.fetchButton)
fetchButton.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
messageTextView.text = "Loading..."
val message = withContext(Dispatchers.IO) {
delay(2000) // Simulate long running task
"Hello from background thread!"
}
messageTextView.text = message
}
}
}
}We use CoroutineScope(Dispatchers.Main).launch to start a coroutine on the main thread because UI updates must happen there.
Inside the coroutine, we first set the TextView to show "Loading..." so the user knows work is in progress.
Then, withContext(Dispatchers.IO) switches the coroutine context to a background thread for the simulated fetch (using delay(2000) to mimic a network or database call).
After the background work finishes, the coroutine resumes on the main thread and updates the TextView with the fetched message.
This pattern keeps the UI responsive and prevents blocking the main thread.