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.