Skip to content

Commit

Permalink
Disallow .listen inside computations
Browse files Browse the repository at this point in the history
  • Loading branch information
mstniy committed Dec 4, 2023
1 parent 3de02d4 commit 1f4167f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
5 changes: 4 additions & 1 deletion lib/src/computed.dart
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class GlobalCtx {
static ComputedImpl get currentComputation {
if (_currentComputation == null) {
throw StateError(
"`use` and `prev` are only allowed inside Computed expressions.");
"`use` and `prev` are only allowed inside computations.");
}
return _currentComputation!;
}
Expand Down Expand Up @@ -208,6 +208,9 @@ class ComputedImpl<T> with Computed<T> {
@override
ComputedSubscription<T> listen(
void Function(T event)? onData, Function? onError) {
if (GlobalCtx._currentComputation != null) {
throw StateError('`listen` is not allowed inside computations.');
}
final sub = _ComputedSubscriptionImpl<T>(this, onData, onError);
if (_novalue) {
try {
Expand Down
28 changes: 24 additions & 4 deletions test/computed_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -832,19 +832,39 @@ void main() {
s.use;
fail("Should have thrown");
} on StateError catch (e) {
expect(e.message,
"`use` and `prev` are only allowed inside Computed expressions.");
expect(
e.message, "`use` and `prev` are only allowed inside computations.");
}

try {
s.prev;
fail("Should have thrown");
} on StateError catch (e) {
expect(e.message,
"`use` and `prev` are only allowed inside Computed expressions.");
expect(
e.message, "`use` and `prev` are only allowed inside computations.");
}
});

test('cannot call listen inside computations', () async {
final c = Computed(() => null);
final c2 = Computed(() => c.listen((event) {}, null));

var flag = false;

c2.listen((event) {
fail("Should not call the listener");
}, (e) {
expect(flag, false);
flag = true;
expect(e, isA<StateError>());
expect(e.message, '`listen` is not allowed inside computations.');
});

await Future.value();

expect(flag, true);
});

group('react', () {
test('can switch from use to react', () async {
// Note that the other direction (react -> use) does not work.
Expand Down

0 comments on commit 1f4167f

Please sign in to comment.