当前位置: 首页 > 工具软件 > bloc > 使用案例 >

Bloc创建流程

从建明
2023-12-01

我们看看前面TestBloc的创建流程

class TestBloc extends Bloc<TestEvent, TestState> {
  TestBloc() : super(TestState()) {
    //获取用户的孩子
    on<LoadTestEvent>(
      (event, emit) async {

        emit(TestSuccessState('Hello'+event.type.toString()));
        return;
      },
    );
  }
}

继承于Bloc

abstract class Bloc<Event, State> extends BlocBase<State>
    implements BlocEventSink<Event> {
  /// {@macro bloc}
  Bloc(State initialState) : super(initialState);

  /// The current [BlocObserver] instance.
  static BlocObserver observer = _DefaultBlocObserver();

  /// The default [EventTransformer] used for all event handlers.
  /// By default all events are processed concurrently.
  ///
  /// If a custom transformer is specified for a particular event handler,
  /// it will take precendence over the global transformer.
  ///
  /// See also:
  ///
  /// * [package:bloc_concurrency](https://pub.dev/packages/bloc_concurrency) for an
  /// opinionated set of event transformers.
  ///
  static EventTransformer<dynamic> transformer = (events, mapper) {
    return events
        .map(mapper)
        .transform<dynamic>(const _FlatMapStreamTransformer<dynamic>());
  };

  final _eventController = StreamController<Event>.broadcast();
  final _subscriptions = <StreamSubscription<dynamic>>[];
  final _handlers = <_Handler>[];
  final _emitters = <_Emitter>[];

这里创建了一个_eventController,Bloc又继承了BlocBase

abstract class BlocBase<State>
    implements StateStreamableSource<State>, Emittable<State>, ErrorSink {
  /// {@macro bloc_base}
  BlocBase(this._state) {
    // ignore: invalid_use_of_protected_member
    _blocObserver.onCreate(this);
  }

  // ignore: deprecated_member_use_from_same_package
  final _blocObserver = BlocOverrides.current?.blocObserver ?? Bloc.observer;

  late final _stateController = StreamController<State>.broadcast();

  State _state;

  bool _emitted = false;

  @override
  State get state => _state;

  @override
  Stream<State> get stream => _stateController.stream;

  /// Whether the bloc is closed.
  ///
  /// A bloc is considered closed once [close] is called.
  /// Subsequent state changes cannot occur within a closed bloc.
  @override
  bool get isClosed => _stateController.isClosed;

这里创建了一个_stateController,

Bloc的大概结构我们了解了,我们看看TestBloc里面的on方法

void on<E extends Event>(
    EventHandler<E, State> handler, {
    EventTransformer<E>? transformer,
  }) {
    assert(() {
      final handlerExists = _handlers.any((handler) => handler.type == E);//检查这个event是否已经处理过
      if (handlerExists) {
        throw StateError(
          'on<$E> was called multiple times. '
          'There should only be a single event handler per event type.',
        );
      }
      _handlers.add(_Handler(isType: (dynamic e) => e is E, type: E));//不存在则添加到_handlers里面
      return true;
    }());

    final _transformer = transformer ?? _eventTransformer;//这里我们没有传transformer 所以这里用的是_eventTransformer
    final subscription = _transformer(
      _eventController.stream.where((event) => event is E).cast<E>(),
      (dynamic event) {
        void onEmit(State state) {
          if (isClosed) return;
          if (this.state == state && _emitted) return;
          onTransition(Transition(
            currentState: this.state,
            event: event as E,
            nextState: state,
          ));
          emit(state);
        }

        final emitter = _Emitter(onEmit);
        final controller = StreamController<E>.broadcast(
          sync: true,
          onCancel: emitter.cancel,
        );

        void handleEvent() async {
          void onDone() {
            emitter.complete();
            _emitters.remove(emitter);
            if (!controller.isClosed) controller.close();
          }

          try {
            _emitters.add(emitter);
            await handler(event as E, emitter);
          } catch (error, stackTrace) {
            onError(error, stackTrace);
            rethrow;
          } finally {
            onDone();
          }
        }

        handleEvent();
        return controller.stream;
      },
    ).listen(null);
    _subscriptions.add(subscription);
  }

这里的_eventTransformer对应Bloc.transformer,

 static EventTransformer<dynamic> transformer = (events, mapper) {
    return events
        .map(mapper)
        .transform<dynamic>(const _FlatMapStreamTransformer<dynamic>());
  };

这里会得到一个_MapStream,它的conver就是我们前面传的匿名函数,然后调用stream的listen方法。然后吧这个subscription添加到_subscriptions

 类似资料: