0
0
Android Kotlinmobile~20 mins

Sealed classes in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Sealed Classes Demo
This screen demonstrates how to use sealed classes in Kotlin to represent different states of a network request and display messages accordingly.
Target UI
-------------------------
| Sealed Classes Demo   |
-------------------------
| Status: Idle          |
|                      |
| [Load Success]        |
| [Load Error]          |
| [Load Loading]        |
-------------------------
Create a sealed class named NetworkResult with three subclasses: Success, Error, and Loading.
Display the current status text on the screen.
Add three buttons labeled 'Load Success', 'Load Error', and 'Load Loading'.
When a button is tapped, update the status text to show the corresponding message from the sealed class.
Use Kotlin Android with Jetpack Compose for UI.
Starter Code
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      MaterialTheme {
        Surface(modifier = Modifier.padding(16.dp)) {
          // TODO: Add your code here
        }
      }
    }
  }
}

// TODO: Define sealed class NetworkResult here
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

sealed class NetworkResult {
  object Success : NetworkResult()
  object Error : NetworkResult()
  object Loading : NetworkResult()
}

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      MaterialTheme {
        Surface(modifier = Modifier.padding(16.dp)) {
          NetworkResultScreen()
        }
      }
    }
  }
}

@Composable
fun NetworkResultScreen() {
  var result by remember { mutableStateOf<NetworkResult?>(null) }

  val statusText = when (result) {
    is NetworkResult.Success -> "Status: Success! Data loaded."
    is NetworkResult.Error -> "Status: Error! Something went wrong."
    is NetworkResult.Loading -> "Status: Loading... Please wait."
    null -> "Status: Idle"
  }

  Column {
    Text(text = statusText, modifier = Modifier.padding(bottom = 16.dp))

    Button(onClick = { result = NetworkResult.Success }, modifier = Modifier.padding(bottom = 8.dp)) {
      Text("Load Success")
    }

    Button(onClick = { result = NetworkResult.Error }, modifier = Modifier.padding(bottom = 8.dp)) {
      Text("Load Error")
    }

    Button(onClick = { result = NetworkResult.Loading }) {
      Text("Load Loading")
    }
  }
}

We defined a sealed class NetworkResult with three subclasses representing different states: Success, Error, and Loading. This helps us group related states in one type.

In the NetworkResultScreen composable, we use a mutable state variable result to hold the current state. We show a text message based on the current state using a when expression.

Three buttons let the user set the state to Success, Error, or Loading. When clicked, the UI updates automatically to show the new status message. This demonstrates how sealed classes help manage state clearly and safely in Kotlin.

Final Result
Completed Screen
-------------------------
| Sealed Classes Demo   |
-------------------------
| Status: Idle          |
|                      |
| [Load Success]        |
| [Load Error]          |
| [Load Loading]        |
-------------------------
Tapping 'Load Success' changes status text to 'Status: Success! Data loaded.'
Tapping 'Load Error' changes status text to 'Status: Error! Something went wrong.'
Tapping 'Load Loading' changes status text to 'Status: Loading... Please wait.'
Stretch Goal
Add a Reset button that sets the status back to Idle.
💡 Hint
Add another button that sets the state variable to null.