Mark
11/01/2023, 8:38 AMFlow
extension fun (taken from here) for collecting single shot events (Android):
@Suppress("ComposableNaming")
@Composable
fun <T> Flow<T>.collectInLaunchedEffectWithLifecycle(
vararg keys: Any?,
lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
collector: suspend CoroutineScope.(T) -> Unit
) {
val flow = this
val currentCollector by rememberUpdatedState(collector)
LaunchedEffect(flow, lifecycle, minActiveState, *keys) {
withContext(Dispatchers.Main.immediate) {
lifecycle.repeatOnLifecycle(minActiveState) {
flow.collect { currentCollector(it) }
}
}
}
}
Joffrey
11/01/2023, 8:39 AMMark
11/01/2023, 8:44 AMZach Klippenstein (he/him) [MOD]
11/01/2023, 5:02 PMDispatchers.Main.immediate
dispatcher explicitly? There are cases where this will actually dispatch later than the compose dispatcher