Line data Source code
1 : /// Mixin that marks a class as holding resources that must be freed.
2 : ///
3 : /// Applied to [Debouncer] to ensure timers are always cancelled
4 : /// when the object is no longer needed, preventing memory leaks.
5 : mixin Disposable {
6 : bool _disposed = false;
7 :
8 : /// Whether [dispose] has already been called on this object.
9 2 : bool get isDisposed => _disposed;
10 :
11 : /// Release all resources held by this object.
12 : ///
13 : /// After calling [dispose], any further calls to [run] will throw
14 : /// a [StateError] to surface bugs early.
15 2 : void dispose() {
16 2 : _disposed = true;
17 2 : onDispose();
18 : }
19 :
20 : /// Override in subclasses to perform actual cleanup.
21 : void onDispose();
22 :
23 : /// Throws if [dispose] has already been called.
24 2 : void assertNotDisposed(String methodName) {
25 2 : if (_disposed) {
26 2 : throw StateError(
27 : 'Cannot call $methodName on a disposed Debouncer. '
28 : 'Create a new Debouncer instance instead.',
29 : );
30 : }
31 : }
32 : }
|