import android.widget.Toast
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.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
@Composable
fun SideEffectsDemo() {
val context = LocalContext.current
val clicked = remember { mutableStateOf(false) }
val log = remember { mutableStateOf("") }
Column(modifier = Modifier.padding(16.dp)) {
Button(onClick = { clicked.value = true }) {
Text("Show Welcome Message")
}
Text(text = "Log: ${log.value}", modifier = Modifier.padding(top = 16.dp))
LaunchedEffect(clicked.value) {
if (clicked.value) {
Toast.makeText(context, "Welcome to Side Effects Demo!", Toast.LENGTH_SHORT).show()
}
}
SideEffect {
if (clicked.value) {
log.value = "Button clicked at ${System.currentTimeMillis()}"
clicked.value = false
}
}
}
}We use clicked state to track button clicks. When the button is clicked, clicked.value becomes true.
LaunchedEffect watches clicked.value. When it changes to true, it shows a Toast message asynchronously without blocking the UI.
SideEffect runs after every successful composition. It updates the log text with the current time and resets clicked.value to false to avoid repeated Toasts.
This way, the UI updates smoothly, showing the Toast and updating the log text below the button.