Skip to content

Commit

Permalink
Add effect: The signals way of creating side effects
Browse files Browse the repository at this point in the history
  • Loading branch information
mstniy committed Dec 25, 2023
1 parent cc8669c commit db8b410
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/computed.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ class Computed<T> {
{required T initialPrev, bool memoized = true, bool async = false})
: _impl = ComputedImpl.withPrev(f, initialPrev, memoized, async);

/// Defines an "effect", which is a computation meant to have side effects.
static ComputedSubscription<void> effect(void Function() f) {
return Computed.async(f).listen(null, null);
}

/// Subscribes to this computation.
///
/// For non-memoized computations, the listener will be called every time
Expand Down
17 changes: 17 additions & 0 deletions test/computed_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,23 @@ void main() {
expect(flag, true);
});

test('effect works', () async {
final s = ValueStream(sync: true);
s.add(42);
int flag = 0;

final c = $(() => s.use);
final effect = Computed.effect(() => flag = c.use);

await Future.value();

expect(flag, 42);
s.add(43);
expect(flag, 43);

effect.cancel();
});

group('streams', () {
test('can be used as data source', () async {
final controller = StreamController<int>.broadcast(
Expand Down

0 comments on commit db8b410

Please sign in to comment.