Skip to content

Commit

Permalink
feat(bloc)!: add throws StateError when bloc is closed (#2912)
Browse files Browse the repository at this point in the history
  • Loading branch information
felangel committed Nov 18, 2021
1 parent 55e01d1 commit ecb0e00
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
6 changes: 3 additions & 3 deletions packages/bloc/lib/src/bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,12 @@ abstract class Bloc<Event, State> extends BlocBase<State> {

/// Notifies the [Bloc] of a new [event] which triggers
/// all corresponding [EventHandler] instances.
/// If [close] has already been called, any subsequent calls to [add] will
/// be ignored and will not result in any subsequent state changes.
///
/// * A [StateError] will be thrown if there is no event handler
/// registered for the incoming [event].
///
/// * A [StateError] will be thrown if the bloc is closed and the
/// [event] will not be processed.
void add(Event event) {
assert(() {
final handlerExists = _handlers.any((handler) => handler.isType(event));
Expand All @@ -264,7 +265,6 @@ abstract class Bloc<Event, State> extends BlocBase<State> {
}
return true;
}());
if (_eventController.isClosed) return;
try {
onEvent(event);
_eventController.add(event);
Expand Down
31 changes: 22 additions & 9 deletions packages/bloc/test/bloc_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1380,10 +1380,13 @@ void main() {
});
});

test('does not trigger onError from add', () {
test(
'add throws StateError and triggers onError '
'when bloc is closed', () {
Object? capturedError;
StackTrace? capturedStacktrace;
var didThrow = false;
runZonedGuarded(() {
Object? capturedError;
StackTrace? capturedStacktrace;
final counterBloc = CounterBloc(
onErrorCallback: (error, stackTrace) {
capturedError = error;
Expand All @@ -1394,17 +1397,27 @@ void main() {
expectLater(
counterBloc.stream,
emitsInOrder(<Matcher>[emitsDone]),
).then((dynamic _) {
expect(capturedError, isNull);
expect(capturedStacktrace, isNull);
});
);

counterBloc
..close()
..add(CounterEvent.increment);
}, (Object _, StackTrace __) {
fail('should not throw when add is called after bloc is closed');
}, (Object error, StackTrace stackTrace) {
didThrow = true;
expect(error, equals(capturedError));
expect(stackTrace, equals(capturedStacktrace));
});

expect(didThrow, isTrue);
expect(
capturedError,
isA<StateError>().having(
(e) => e.message,
'message',
'Cannot add new events after calling close',
),
);
expect(capturedStacktrace, isNotNull);
});
});

Expand Down

0 comments on commit ecb0e00

Please sign in to comment.