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?
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?
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.
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)
}
}
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.
Just use LaunchedEffect with repeatOnLifecycle. Without repeatOnLifecycle, your flow will be collected even when the app is in the background.
Eg.
@Composable
fun YourFunction() {
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(Unit) {
repeatOnLifecycle(Lifecycle.State.STARTED) {
withContext(Dispatchers.Main.immediate) {
sharedFlow
.collect { /* doSomething */ }
}
}
}
}
Anyway, I suggest using channels instead of shared flows, if the flow is collected in only one place as it has built-in buffer so you will not miss any event.
You can find more explanation in Philipp Lackner video about One-Time Events in Jetpack Compose
© 2022 - 2025 — McMap. All rights reserved.