https://kotlinlang.org logo
#codereview
Title
# codereview
m

Mark

11/01/2023, 8:38 AM
Thoughts on this
Flow
extension fun (taken from here) for collecting single shot events (Android):
Copy code
@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) }
      }
    }
  }
}
j

Joffrey

11/01/2023, 8:39 AM
Mmmh, how about not using a Flow for single shot events? Flows are for streams of values and suspend functions are for single values
1
m

Mark

11/01/2023, 8:44 AM
Perhaps use a viewmodel MutableState (nullable value) and get the UI to null it when done? Or do you have a specific solution in mind?
z

Zach Klippenstein (he/him) [MOD]

11/01/2023, 5:02 PM
Why use the
Dispatchers.Main.immediate
dispatcher explicitly? There are cases where this will actually dispatch later than the compose dispatcher