Reputation: 11
I need to execute multiple events from different Blocs synchronously, ensuring that each event completes before the next one starts. Here's the current code:
context.read<PaymentBloc>().add(GetSubscriptionDetails());
context.read<HeartCounterBloc>().add(GetHeartValueEvent());
context.read<StreakBloc>().add(GetStreakInfoEvent());
context.read<ChatBloc>().add(UpdateUserStatusEvent(
userId: context.read<UserProvider>().user.id, status: true,
));
The above code dispatches all events at once, but I want them to execute one after another, waiting for each event to complete before starting the next one.
Is there a better way to execute events from different Blocs synchronously?
Can Bloc Concurrency help here, or is there another recommended approach?
Are there any best practices for handling such scenarios?
I tried using await with stream.firstWhere to wait for the state changes, but that makes little complex thing, is there any way to achieve without complex things
Note : Those block have dependancy on other things, so its not easy to create a obj directly
Upvotes: 1
Views: 25
Reputation: 2541
As follows from the documentation, there are no other good ways to link blocks: it's either listenrs in UI or some logic at the repository level.
As for UI level you should probably use MultiBlocListener. You could easy listening every bloc that you need and react to state of this bloc as you need.
Something like:
@override
void initState(){
context.read<PaymentBloc>().add(GetSubscriptionDetails());
}
or
onTap:(){
context.read<PaymentBloc>().add(GetSubscriptionDetails());
}
And then some where in UI:
@override
Widget build(BuildContext context) {
return MultiBlocListener(
listeners: [
BlocListener<PaymentBloc, PaymentState>(
listener: (_, state) {
if (state !is StateThatYouShoulReact or other condition) return;
context.read<HeartCounterBloc>().add(GetHeartValueEvent());
},
),
BlocListener<HeartCounterBloc, HeartCounterState>(
listener: (_, state) {
..//do stuff
}
},
),
BlocListener<StreakBloc, StreakState>(
listener: (_, state) {
..//do stuff
}
},
),
BlocListener<ChatBloc, ChatState>(
listener: (_, state) {
..//do stuff
}
},
),
],
child: child,
);
}
}
Upvotes: 0