0
0
Android Kotlinmobile~20 mins

withContext for thread switching in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Thread Switch Demo
This screen shows how to switch threads using withContext in Kotlin coroutines. It fetches a message on a background thread and updates the UI on the main thread.
Target UI
-------------------------
| Thread Switch Demo    |
|-----------------------|
|                       |
| Message:               |
| [Loading...]           |
|                       |
| [Fetch Message Button] |
-------------------------
Add a Button labeled 'Fetch Message Button'.
When tapped, start a coroutine that switches to a background thread to simulate fetching data.
Use withContext(Dispatchers.IO) to switch to background thread.
After fetching, switch back to the main thread to update the TextView with the fetched message.
Show 'Loading...' text while fetching.
Starter Code
Android Kotlin
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 {
            // TODO: Add coroutine to fetch message with thread switching
        }
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
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.

Final Result
Completed Screen
-------------------------
| Thread Switch Demo    |
|-----------------------|
|                       |
| Message:               |
| Hello from background  |
| thread!                |
|                       |
| [Fetch Message Button] |
-------------------------
User taps 'Fetch Message Button'.
TextView changes to 'Loading...'.
After 2 seconds, TextView updates to 'Hello from background thread!'.
Stretch Goal
Add a ProgressBar that shows while fetching and hides after completion.
💡 Hint
Use ProgressBar visibility properties and show it before withContext, hide it after updating the message.