What is the best practice for listening to another bloc’s state changes?
This answer was relevant in previous version, but it doesn’t work in version 8 (.listen
method doesn’t exist anymore on a bloc): https://stackoverflow.com/a/62785980/160919
FilteredTodosBloc({@required this.todosBloc}) {
todosSubscription = todosBloc.listen((state) {
if (state is TodosLoadSuccess) {
add(TodosUpdated((todosBloc.state as TodosLoadSuccess).todos));
}
});}
What is the recommended approach to listen to a state change from another bloc in flutter_bloc 8?
CodePudding user response:
State stream is now exposed via stream
getter, so you can still use almost the same code:
FilteredTodosBloc({required this.todosBloc}) {
todosSubscription = todosBloc.stream.listen((state) {
if (state is TodosLoadSuccess) {
add(TodosUpdated((todosBloc.state as TodosLoadSuccess).todos));
}
});}
CodePudding user response:
Nothing really changed in terms of recommended approach. All you have to do is call stream
property first and listen to it intead of bloc directly. So if you previously listened to blocs / cubits like this:
myBloc.listen((state) => print(state));
all you need to change is call stream
first, like this:
myBloc.stream.listen((state) => print(state));