79 lines
1.8 KiB
Dart
79 lines
1.8 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:meta/meta.dart';
|
|
|
|
// 简易的Bloc, 简易的状态管理
|
|
|
|
abstract class EasyBlocBase<State> {
|
|
|
|
EasyBlocBase(this.state): assert(state != null);
|
|
|
|
final StreamController<State> _stateController = StreamController<State>.broadcast();
|
|
|
|
Stream<State> get stream => _stateController.stream;
|
|
State state;
|
|
|
|
bool _emitted = false;
|
|
|
|
// 添加监听器方法
|
|
StreamSubscription<State> listen(
|
|
void Function(State state) onData, {
|
|
Function? onError,
|
|
void Function()? onDone,
|
|
bool? cancelOnError,
|
|
}) {
|
|
return stream.listen(
|
|
onData,
|
|
onError: onError,
|
|
onDone: onDone,
|
|
cancelOnError: cancelOnError,
|
|
);
|
|
}
|
|
|
|
// 新状态
|
|
void emit(State newState) {
|
|
if (_stateController.isClosed) return;
|
|
if (newState == state && _emitted) return;
|
|
this.state = newState;
|
|
_stateController.add(state);
|
|
_emitted = true;
|
|
}
|
|
|
|
@mustCallSuper
|
|
Future<void> close() async {
|
|
await _stateController.close();
|
|
}
|
|
}
|
|
|
|
class EasyBloc<Event, State> extends EasyBlocBase<State> {
|
|
EasyBloc(State initialState) : super(initialState) {
|
|
_eventController.stream.listen(_mapEventToState);
|
|
}
|
|
|
|
final StreamController<Event> _eventController = StreamController<Event>();
|
|
|
|
// 子类需要实现这个方法来处理事件
|
|
@mustBeOverridden
|
|
void _mapEventToState(Event event) {
|
|
// 默认不做任何处理,如果不实现会抛出异常
|
|
throw UnimplementedError('_mapEventToState must be implemented by subclasses');
|
|
}
|
|
|
|
// 添加事件
|
|
void add(Event event) {
|
|
if (_eventController.isClosed) return;
|
|
_eventController.add(event);
|
|
}
|
|
|
|
@override
|
|
Future<void> close() async {
|
|
await _eventController.close();
|
|
await super.close();
|
|
}
|
|
}
|
|
|
|
class EasyCubit<State> extends EasyBlocBase<State> {
|
|
EasyCubit(State initialState) : super(initialState);
|
|
}
|
|
|