Skip to content

Commit

Permalink
Merge pull request #120 from jinyus/guarded-disposal
Browse files Browse the repository at this point in the history
Add disposal guard for beacons
  • Loading branch information
jinyus authored Jan 2, 2025
2 parents 67ab921 + 87c4ca4 commit c4f1545
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/state_beacon_core/lib/src/extensions/wrap.dart
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ extension WritableWrap<T, U> on BeaconWrapper<T, U> {
});

onDispose(() {
if (isDisposing) return;
if (isDisposing || target._guarded) return;
isDisposing = true;
target.dispose();
});
Expand Down
17 changes: 17 additions & 0 deletions packages/state_beacon_core/lib/src/producer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,23 @@ abstract class Producer<T> implements Disposable {
}
}

/// This is true if the beacon is guarded from being disposed by
/// its dependants.
bool _guarded = false;

/// Prevents the beacon from being disposed by its dependants.
/// The beacon will still be disposed if its dependencies are disposed.
///
/// ```dart
/// final number = Beacon(0)..guard();
/// final doubled = number.map((value) => value * 2);
/// doubled.dispose();
/// number.disposed; // false
/// ```
void guard() {
_guarded = true;
}

/// The number of listeners subscribed to this beacon.
int get listenersCount => _observers.length;

Expand Down
22 changes: 22 additions & 0 deletions packages/state_beacon_core/test/src/beacons/readable_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,26 @@ void main() {
beacon.value = 1;
beacon.value = 2;
});

test('should not dispose when dependant is disposed when guarded', () {
final number = Beacon.writable(0);

number.guard();

final doubled = number.map((value) => value * 2);

doubled.dispose();

expect(number.isDisposed, false);
});

test('should dispose when dependant is disposed when not guarded', () {
final number = Beacon.writable(0);

final doubled = number.map((value) => value * 2);

doubled.dispose();

expect(number.isDisposed, true);
});
}

0 comments on commit c4f1545

Please sign in to comment.