skip to Main Content

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


  1. No it isn’t bad practice to use a StreamController in a Cubit. Cubits are designed not to be event driven and StreamController can be used to update the state of Cubit on Stream changes.

    Reference

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search