How to run BlocObserver example in cli

Chris G.

Update: As @oleksa found, the solution is just create/attach the MyBlocObserver before the BloC.

I was hoping to be able to test BlocObserver in a simple dart cli.

import 'package:bloc/bloc.dart';

void main(){
  MyBloc myBloc = MyBloc(); // << just standard Bloc
  Bloc.observer = MyBlocObserver();

  myBloc.add(NewEvent(eventName: "Test"));
}

class MyBlocObserver extends BlocObserver {

  @override
  void onChange(BlocBase bloc, Change change) {
    print("onChange");
    super.onChange(bloc, change);
  }

  @override
  void onCreate(BlocBase bloc) {
    print("onCreate");
    super.onCreate(bloc);
  }

  @override
  void onClose(BlocBase bloc) {
    print("onClose");
    super.onClose(bloc);
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    print("onError");
    super.onError(bloc, error, stackTrace);
  }

  @override
  void onEvent(Bloc bloc, Object? event) {
    print("onEvent");
    super.onEvent(bloc, event);
  }
}
oleksa

I'm not sure that understood the question since there is no question actually.

However I'd like to suggest you and review the Bloc observer concept

I tried the concept sample code and found it works as it should:

// The event and block classes

abstract class CounterEvent {}

class CounterIncrementPressed extends CounterEvent {}

class CounterBloc extends Bloc<CounterEvent, int> {
  CounterBloc() : super(0) {
    on<CounterIncrementPressed>((event, emit) {
      // handle incoming `CounterIncrementPressed` event
      emit(state + 1);
    });
  }
}
/// bloc observer that observes bloc events

class SimpleBlocObserver extends BlocObserver {
  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    print('${bloc.runtimeType} $change');
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print('${bloc.runtimeType} $transition');
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    print('${bloc.runtimeType} $error $stackTrace');
    super.onError(bloc, error, stackTrace);
  }
}

and main function as below

void main() {
  Bloc.observer = SimpleBlocObserver();
  CounterBloc()
    ..add(CounterIncrementPressed())
    ..close();
}

You may want to create observer first. I've tried to create the bloc before the observer and it stopped to work.

I suppose that the Bloc.observer instance is used by the Bloc derived instance to initiate a subscription.

Below you can see the sample of changes

  Bloc.observer = MyBlocObserver();
  MyBloc myBloc = MyBloc(); // created after Bloc.observer initialization

  myBloc.add(NewEvent(eventName: "Test"));

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive