Home > database >  How to use SharedFlow in Jetpack Compose
How to use SharedFlow in Jetpack Compose

Time:03-26

With state flow I can use

val items by myViewModel.items.collectAsState()

I suppose shared flow cannot be used this way. Are shared flows even applicable for Compose?

CodePudding user response:

Technically you can collect it as state as any other Flow - with an initial value:

flow.collectAsState(initial = 0)

This state will have the last value emitted by the flow during the time of view being presented, or the initial value. I'm not sure this makes much sense, though.

But you can also use it as a way to deliver events that require a one-time response, as shown in this answer.

CodePudding user response:

SharedFlow should be used for one-shot events(navigation, toast, etc... ).

So this is the way to collect a SharedFlow:

@Composable
fun <T> Flow<T>.collectAsEffect(
    context: CoroutineContext = EmptyCoroutineContext,
    block: (T) -> Unit
) {
    LaunchedEffect(key1 = Unit) {
        onEach(block).flowOn(context).launchIn(this)
    }
}
  • Related