Skip to content

Commit

Permalink
feat: Add onInitialState to FlameBlocListener (#2565)
Browse files Browse the repository at this point in the history
Adding onInitialState to FlameBlocListener to match the implemented interface.
  • Loading branch information
erickzanardo authored Jun 7, 2023
1 parent 34e5f0e commit f440bbf
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/flame_bloc/lib/src/flame_bloc_listener.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,27 @@ class FlameBlocListener<B extends BlocBase<S>, S> extends Component
/// {@macro flame_bloc_listener}
FlameBlocListener({
required void Function(S state) onNewState,
void Function(S state)? onInitialState,
B? bloc,
bool Function(S previousState, S newState)? listenWhen,
}) : _onNewState = onNewState,
_onInitialState = onInitialState,
_listenWhen = listenWhen {
if (bloc != null) {
this.bloc = bloc;
}
}

final void Function(S state) _onNewState;
final void Function(S state)? _onInitialState;
final bool Function(S previousState, S newState)? _listenWhen;

@override
void onNewState(S state) => _onNewState(state);

@override
void onInitialState(S state) => _onInitialState?.call(state);

@override
bool listenWhen(S previousState, S newState) {
return _listenWhen?.call(previousState, newState) ?? true;
Expand Down
22 changes: 22 additions & 0 deletions packages/flame_bloc/test/src/flame_bloc_listener_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,28 @@ void main() {
},
);

testWithFlameGame(
'onInitialState is called when the initial state is received',
(game) async {
final bloc = PlayerCubit();
final provider = FlameBlocProvider<PlayerCubit, PlayerState>.value(
value: bloc,
);
final states = <PlayerState>[];
await game.ensureAdd(provider);

final component = FlameBlocListener<PlayerCubit, PlayerState>(
onNewState: (_) {},
onInitialState: states.add,
);
await provider.ensureAdd(component);

bloc.kill();
await Future.microtask(() {});
expect(states, equals([PlayerState.alive]));
},
);

testWithFlameGame(
'onNewsState is not called when listenWhen returns false',
(game) async {
Expand Down

0 comments on commit f440bbf

Please sign in to comment.