bloc
bloc copied to clipboard
Question: How to comunicate between 2 Blocs based on Repositrory stream
Description
I have UserRepository
to store the User information for entire app and I want to listen it from any place in app
I researched solution from document and tried use stream from UserRepository to manage UserInformation
but I faced a new problem.
Before
- Screen A(Bloc A) -> open Screen B(Bloc B)
Steps
- Go to Screen A
- Update User information at UserRepository from Bloc A
- Go to Screen B
- In bloc B, listen user information from UserRepository stream and get newest User information
Problem Can't listen new User information at Bloc B
Expected Behavior Get newest User information is updated from bloc A before
Please let me know if want to any more information
Sorry, I can't change the label
Hi @luudan0079 š Thanks for opening an issue!
I recommend that both blocs A and B are listening to the same stream exposed by the repository. This will ensure that the two are kept in sync. If you're still having trouble, can you please share a link to a minimal reproduction sample? Thanks! š
@felangel thanks for quick response!
Please check sample code(Sorry for syntax, hope you undertand).
In below code, I have a UserRepository(singleton).
At screenA, I have BlocA and use streamController
to emited EventBBB
and open screenB after that.
At screenB, I have BlocB and listen same streamController
.
- Expected: Received
EventBBB
at BlocB - Actual: Not Received
EventBBB
at BlocB
class UserRepository { // Singleton
StreamController<CustomDioError> streamController =
StreamController<CustomDioError>.broadcast();
}
class BlocA {
UserRepository userRepository = UserRepository(); //getSingleTon
void _initFunction() {
userRepository.streamController.stream.listen((Event event) {
print('Bloc A $event');
});
}
void _emitValue() {
userRepository.streamController.add(EventBBB());
}
}
class BlocB {
UserRepository userRepository = UserRepository(); // getSingleTon
void _initFunction() {
emitter.forEach(userRepository.streamController.stream, onData: (Event event)) {
print('Bloc B $event'); // expected: EventBBB
}
}
}
If you have any concern about sample, please let me know. Thank you so much
@luudan0079 I think that's because you have created two separate instances of UserRepository
in each of your blocs, means they are not really singletons. An easy way to fix that is to take in an instance of UserRepository
as a parameter of the constructor of your blocs, and then listen to the stream like you already did.
@yshean Hi,
UserRepository
is Singleton. I think main problem come from Stream.dart
That's not a minimal reproduction sample. Please provide a link to a repo with an sample app which can be started to actually see that behavior.
Closing for now since there are no actionable next steps. Feel free to provide a minimal reproduction sample if this is still an issue and Iām happy to take a look š