Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active February 28, 2026 23:15
Show Gist options
  • Select an option

  • Save benigumocom/1fc2ba6d5fd21b31b5ff84e0ad0ae3c8 to your computer and use it in GitHub Desktop.

Select an option

Save benigumocom/1fc2ba6d5fd21b31b5ff84e0ad0ae3c8 to your computer and use it in GitHub Desktop.
How to handle UI interactions with event processing
// No ViewModel
@Composable
fun UiOnlySample() {
val context = LocalContext.current
Button(onClick = {
Toast.makeText(context, "Clicked!", Toast.LENGTH_SHORT).show()
}) {
Text("Click")
}
}
// State Management
class StateFlowViewModel : ViewModel() {
private val _state = MutableStateFlow("initial")
val state = _state.asStateFlow()
fun update() {
_state.value = "updated at " + System.currentTimeMillis()
}
}
@Composable
fun StateFlowSample(vm: StateFlowViewModel = viewModel()) {
val value by vm.state.collectAsState()
Column {
Text(value)
Button(onClick = { vm.update() }) {
Text("Update")
}
}
}
// One-Shot Events
class SharedFlowViewModel : ViewModel() {
private val _event = MutableSharedFlow<String>(
replay = 0,
extraBufferCapacity = 1 // One-shot
)
val event = _event.asSharedFlow()
fun sendEvent() {
_event.tryEmit("Hello from SharedFlow!")
}
}
@Composable
fun SharedFlowSample(vm: SharedFlowViewModel = viewModel()) {
val context = LocalContext.current
LaunchedEffect(Unit) {
vm.event.collect { msg ->
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
}
}
Button(onClick = { vm.sendEvent() }) {
Text("Send Event")
}
}
// Strict One-Time + Ordered Delivery
class ChannelViewModel : ViewModel() {
private val _channel = Channel<String>(capacity = Channel.BUFFERED)
val eventFlow = _channel.receiveAsFlow()
fun sendEvent() {
viewModelScope.launch {
_channel.send("Hello from Channel!")
}
}
}
@Composable
fun ChannelSample(vm: ChannelViewModel = viewModel()) {
val context = LocalContext.current
LaunchedEffect(Unit) {
vm.eventFlow.collect { msg ->
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
}
}
Button(onClick = { vm.sendEvent() }) {
Text("Send Event")
}
}
@benigumocom
Copy link
Copy Markdown
Author

benigumocom commented Feb 28, 2026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment