-
Define the Interface:
First, ensure you have an interface that exposes the Flow<Boolean>. For example:
interface BooleanFlowProvider {
val booleanFlow: Flow<Boolean>
}
-
Create a CompositionLocal:
Define a CompositionLocal for your interface. This allows you to provide and consume the flow throughout the composable hierarchy.
val LocalBooleanFlowProvider = compositionLocalOf<BooleanFlowProvider> {
error("No BooleanFlowProvider provided")
}
-
Implement the Interface in Your Composable:
In your top-level composable (e.g., the screen composable within your Activity), obtain the ViewModel and provide an implementation of the interface using CompositionLocalProvider.
@Composable
fun MyScreen(navigator: Navigator) {
// Obtain the ViewModel via Voyager's navigator
val viewModel: MyViewModel = navigator.getViewModel()
// Create an implementation of BooleanFlowProvider
val booleanFlowProvider = remember {
object : BooleanFlowProvider {
override val booleanFlow: Flow<Boolean> = viewModel.myBooleanFlow
}
}
// Provide the implementation to the CompositionLocal
CompositionLocalProvider(LocalBooleanFlowProvider provides booleanFlowProvider) {
// Your screen's UI hierarchy
MyContent()
}
}
-
Consume the Flow in Deep Composables:
In any nested composable, you can access the Flow<Boolean> via the CompositionLocal and collect it as state using collectAsState. This allows the UI to react to changes in the flow.
@Composable
fun MyContent() {
// Other UI components
// Deep composable that needs the boolean flow
DeepChildComposable()
}
@Composable
fun DeepChildComposable() {
// Access the BooleanFlowProvider from CompositionLocal
val booleanFlowProvider = LocalBooleanFlowProvider.current
// Collect the flow as state
val isVisible by booleanFlowProvider.booleanFlow.collectAsState(initial = false)
// Use the state in your UI
if (isVisible) {
// Show some UI component
Text("Visible!")
} else {
// Show alternative UI
Text("Not Visible.")
}
}
-
ViewModel Example:
Ensure your ViewModel exposes the Flow<Boolean> correctly. For example:
class MyViewModel : ViewModel() {
private val _myBooleanFlow = MutableStateFlow(false)
val myBooleanFlow: Flow<Boolean> = _myBooleanFlow.asStateFlow()
// Function to toggle the flow value
fun toggleVisibility() {
_myBooleanFlow.value = !_myBooleanFlow.value
}
}
-
Triggering Flow Changes:
You can trigger changes in the Flow<Boolean> from anywhere in your composables by accessing the ViewModel. For example:
@Composable
fun ToggleButton(navigator: Navigator) {
val viewModel: MyViewModel = navigator.getViewModel()
Button(onClick = { viewModel.toggleVisibility() }) {
Text("Toggle Visibility")
}
}