flutterdartbloc

Is it bad practice to have a cubit listen to a StreamController?


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.


Solution

  • I'd say using a StreamController in a Cubit could be a code smell because a Cubit is itself - in a sense - a StreamController where cubit.emit is similar to streamController.add, so it would beg the question: why a StreamController is even needed?

    However, in your code you are not actually using a StreamController in the Cubit. You are only using the Stream part of it.

    Listening to a Stream in a Cubit is a valid use case.