Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/flame_bloc/lib/src/flame_bloc_listenable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ mixin FlameBlocListenable<B extends BlocBase<S>, S> on Component {
late StreamSubscription<S> _subscription;
late B _bloc;
B? _blocOverride;
bool _blocInitialized = false;

/// Returns the bloc that this component is reading from once the component
/// has been mounted.
B get bloc {
assert(
isMounted,
_blocInitialized,
'Cannot access the bloc instance before it has been mounted.',
);
return _bloc;
Expand Down Expand Up @@ -49,6 +50,7 @@ mixin FlameBlocListenable<B extends BlocBase<S>, S> on Component {
_blocOverride = bloc = provider.bloc;
}
_bloc = bloc;
_blocInitialized = true;
_state = bloc.state;
onInitialState(_state);
_subscription = bloc.stream.listen((newState) {
Expand Down Expand Up @@ -84,5 +86,6 @@ mixin FlameBlocListenable<B extends BlocBase<S>, S> on Component {
void onRemove() {
super.onRemove();
_subscription.cancel();
_blocInitialized = false;
}
}
27 changes: 27 additions & 0 deletions packages/flame_bloc/test/src/flame_bloc_listenable_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,17 @@ class _SadPlayerListener extends Component
}
}

class _BlocAccessingListener extends Component
with FlameBlocListenable<PlayerCubit, PlayerState> {
PlayerCubit? initialBloc;

@override
void onInitialState(PlayerState state) {
super.onInitialState(state);
initialBloc = bloc;
}
}

void main() {
group('FlameBlocListenable', () {
testWithFlameGame(
Expand Down Expand Up @@ -130,6 +141,22 @@ void main() {
},
);

testWithFlameGame(
'can access bloc in onInitialState',
(game) async {
final bloc = PlayerCubit();
final provider = FlameBlocProvider<PlayerCubit, PlayerState>.value(
value: bloc,
);
await game.ensureAdd(provider);

final component = _BlocAccessingListener();
await provider.ensureAdd(component);

expect(component.initialBloc, bloc);
},
);

testWithFlameGame(
'successfully revisit previously visited route with bloc listener',
(game) async {
Expand Down
Loading