Flutter › State Management with BLoC & Cubit
How do BLoC to BLoC communication patterns work, letting one given BLoC properly react to a genuinely separate other BLoC's own emitted state changes, such as a cart BLoC properly reacting whenever a genuinely separate authentication BLoC's own state actually changes?
IntermediateAnswer
BLoC to BLoC communication typically involves one particular BLoC properly subscribing directly to a genuinely separate other BLoC's own state stream, often within its own constructor, and reacting appropriately whenever that particular other BLoC emits a genuinely new state, such as a CartBloc properly clearing its own entire cart state the very instant an AuthBloc's own emitted state indicates that a user has genuinely just logged out, and while this particular pattern is genuinely quite useful, it should generally still be used somewhat sparingly, since excessive direct coupling between several separate individual BLoCs can meaningfully begin to reduce their own overall individual testability and genuine independence from one another.
class CartBloc extends Bloc<CartEvent, CartState> {
CartBloc(AuthBloc authBloc) : super(CartState.empty()) {
authBloc.stream.listen((authState) {
if (authState is LoggedOut) add(ClearCart());
});
}
}Real-world example A shopping app's CartBloc properly listens directly to its AuthBloc's own state stream, automatically clearing the entire current cart the very instant a user genuinely logs out, correctly ensuring one user's own cart contents can never accidentally carry over into a genuinely separate different user's own subsequent session.