Bloc Provider
A composable that registers StateEmitter instances (Bloc or Cubit) with BlocRegistry and makes them available to any descendant composable.
BlocProvider is the entry point for the Bloc pattern in Compose. It handles the full lifecycle of the provided blocs: they are registered when the composable enters composition and closed + deregistered when it leaves.
Overview
Wrap your root composable (or any subtree) with BlocProvider:
setContent {
BlocProvider(listOf(
CounterBloc(),
AuthBloc(authService = LiveAuthService()),
)) {
AppNavigation()
}
}Content copied to clipboard
Dependency injection
BlocProvider is the ideal place to inject dependencies into your blocs:
BlocProvider(listOf(
UserBloc(userService = LiveUserService()),
AnalyticsBloc(tracker = FirebaseTracker()),
)) {
MainScreen()
}Content copied to clipboard
For Compose previews and tests, swap in mock implementations:
@Preview
@Composable
fun CounterPreview() {
BlocProvider(listOf(CounterBloc())) {
CounterScreen()
}
}Content copied to clipboard
Accessing blocs
Resolve blocs anywhere in the descendant tree via BlocRegistry.resolve:
@Composable
fun CounterScreen() {
val bloc = remember { BlocRegistry.resolve(CounterBloc::class) }
val state by bloc.stateFlow.collectAsState()
Text("Count: ${state.count}")
}Content copied to clipboard
Parameters
blocs
The list of StateEmitter instances to register.
content
The composable subtree that can resolve registered blocs.