Skip to content

Instantly share code, notes, and snippets.

@ajinkya5130
Created September 28, 2025 15:22
Show Gist options
  • Select an option

  • Save ajinkya5130/eb973b53e94ff669595d586129c81a48 to your computer and use it in GitHub Desktop.

Select an option

Save ajinkya5130/eb973b53e94ff669595d586129c81a48 to your computer and use it in GitHub Desktop.
One time Event Observer
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
@Composable
fun <T>ObserveEvent(
flow: Flow<T>,
key1:Any? = null,
key2:Any? = null,
onEvent:(T) -> Unit
){
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(lifecycleOwner,key1,key2){
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