I have BlocA which need to change its stated based on Events of BlocB
@felangel How BlocA can listen to Events of BlocB?
I don't think you can listen to events of BlocB from BlocA. What you can do is listen to BlocB's state or pass BlocA to BlocB as a construct param and add BlocB's event to BlocA whenever a new event is added to BlocB. But using the second option will make each bloc dependent on one another.
Here is the implementation of the first option.
class BlocA extends Bloc<String, String> {
StreamSubscription _streamSubscription;
BlocA(BlocB blocB) : super('') {
// You can start listening when some event is added by moving the next line
// to mapEventToState method and addint some condition
_streamSubscription = blocB.listen(_doSomething);
}
@override
Stream<String> mapEventToState(String event) {
// TODO: implement mapEventToState
}
// value is the state of BlocB
void _doSomething(String value) {
// TODO: do something here
}
@override
Future<void> close() {
_streamSubscription?.cancel();
return super.close();
}
}
class BlocB extends Bloc<String, String> {
BlocB() : super('initial');
@override
Stream<String> mapEventToState(String event) {
// TODO: implement mapEventToState
}
}
Hi @sm2017 馃憢
Thanks for opening an issue!
As @Elias8 pointed out, generally blocs and ui can react and listen to states of other blocs but they should not listen to the events.
In addition to the approach @Elias8 provided you can also use BlocListener
BlocListener<BlocB, StateB>(
listener: (context, state) {
context.read<BlocA>().add(SomeEventInResponseToStateBChanging());
},
child: ...
)
Hope that helps 馃憤
@felangel I am writing a complex application, states in different blocs is closely related to each other , let me explain with a minimal hypothetical example
I have MyProjects , FavoriteProjects, ProjectDetails, each project has it own attachments , When you have Uploaded and Deleted event in an attachments, or Favorited and Unfavorited event in a project I must update all 3 blocs
int id
String title
bool isFavorited
List attachments
int id
string filename
string url
There are different ways to achieve what you are saying, it would be easier to help if you have a repo that you could share. Before that, check out this or full project example, I think it is the same thing as you described above but with one bloc.