flutter_bloc – hook into onClose, onCreate lifecycle events for specific cubit

Issue

I want to hook into the lifecycle events of my cubits.

I notice the blocObserver has onClose and onCreate, however that is for observing all cubit’s lifecycle events. How do I hook into these events just for a specific cubit? For example the equivalent of overriding onClose inside a cubit.

My implementation of ChessMax’s answer:

class VpCubit<T> extends Cubit<T> {
  VpCubit(T initial) : super(initial);

  void onClose() => print('');

  @override
  Future<void> close() async {
    if (onClose != null) {
      onClose();
    }

    return super.close();
  }
}

class LoggedOutNickNameCubit extends VpCubit<int> {
  LoggedOutNickNameCubit()
      : super(0);

  @override
  void onClose() {
    print('closing');
  }

  void onCreate() {
    print('creating');
  }
}

Solution

One possible solution is to filter out events in the observing hook. Every event of BlocObserver has a reference to a cubit/bloc instance that sends the event. So you can compare it with the reference with your specific cubit/bloc instance. And if references are equal you can handle it somehow. Something like this:

  class MyObserver extends BlocObserver {

  final Cubit<Object> _cubit;

  MyObserver(this._cubit) : assert(_cubit != null);

  @override
  void onClose(Cubit cubit) {
    if (cubit == _cubit) {
      // do whatever you need
    }
    
    super.onClose(cubit);
  }
}

Another way is to create your own cubit/bloc subclass. Override the methods you want to listen to. And use your own BlocObserver like class to notify this specific cubit/bloc listeners. Something like this:

class MyObserver {
  final void Function() onClose;

  MyObserver(this.onClose);  
}

class MyBloc extends Bloc<MyEvent, MyState> {
  final MyObserver _observer;
  MyBloc(this._observer) : super(MyInitial());


  @override
  Future<void> close() async {
    if (_observer != null && _observer.onClose != null) {
      _observer.onClose();
    }
    
    return super.close();
  }
}

Also, I think, it’s possible to write a generic cubit/bloc wrapper base class like above. And then use it as a base class for all your cubits/blocs classes instead.

Answered By – ChessMax

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *