Skip to content

Instantly share code, notes, and snippets.

@cavin-macwan
Created April 9, 2025 06:28
Show Gist options
  • Save cavin-macwan/42b770df43a4ed3e691be6ad51bb4866 to your computer and use it in GitHub Desktop.
Save cavin-macwan/42b770df43a4ed3e691be6ad51bb4866 to your computer and use it in GitHub Desktop.
This snippet allows you to collect one time events like showing the snackbar or navigation without being lost
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
/**
* Use it like this
*
* Inside the **ViewModel**:
*
* ```
* private val _events = Channel<UiEvent>()
* val events = _events.receiveAsFlow()
*
* fun sendEvent(){
* _events.send(UiEvent.NavigateToHome)
* }
*
* sealed interface UiEvent {
* object NavigateToHome: UiEvent
* }
* ```
*
* Inside the **UI**
* ```kotlin
* ObserveAsEvents (viewModel.events) {
* when (event) {
* is UiEvent.NavigateToHome -> {
* navController.navigate(route: HOME)
* }
* }
* }
* ```
*/
@Composable
private fun <T> ObserveAsEvents(flow: Flow<T>, onEvent: (T) -> Unit) {
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(flow, lifecycleOwner.lifecycle) {
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
withContext(Dispatchers.Main.immediate) {
flow.collect(onEvent)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment