We have a data repository in the backend which is hooked up to a realtime supabase table. Everytime there are certain changes we are listening for, the data repository is notifying our Cubit of the changes:
/// Stream controller for notifying cubit about data changes.
final StreamController<void> _dataChangeController =
StreamController<void>.broadcast();
Stream<void> get onDataChanged => _dataChangeController.stream;
And in the Cubit:
// Initialize new data repository
await DataRepository.instance.init(locale);
_dataRepository = DataRepository.instance;
// Listen for data changes
_occupancySubscription =
_dataRepository!.onDataChanged.listen((_) => refreshSpots());
I’m sorry if this is a dumb question, as this is surely bad practice, but then is it preferable to use a Bloc instead in this situation?
Thank you in advance, I just want to learn.
2
Answers
No it isn’t bad practice to use a
StreamController
in aCubit
. Cubits are designed not to be event driven and StreamController can be used to update the state of Cubit on Stream changes.Reference
I’d say using a
StreamController
in aCubit
could be a code smell because aCubit
is itself – in a sense – aStreamController
wherecubit.emit
is similar tostreamController.add
, so it would beg the question: why aStreamController
is even needed?However, in your code you are not actually using a
StreamController
in theCubit
. You are only using theStream
part of it.Listening to a
Stream
in aCubit
is a valid use case.