Disposable class

Allows the creation of managed objects, including helpers for common patterns.

We recommend consuming this class in one of two ways.

  1. As a base class
  2. As a concrete proxy

We do not recommend using this class as a mixin or as an interface. Use as a mixin can cause the onDispose method to be shadowed. Use as an interface is just cumbersome.

If an interface is desired, the DisposableManager... interfaces are available.

In the case below, the class is used as a mixin. This provides both default implementations and flexibility since it does not occupy a spot in the class hierarchy. However, consumers should use caution if they choose to employ this pattern.

Helper methods, such as listenToStream allow certain cleanup to be automated. Managed subscriptions will be automatically canceled when dispose is called on the object.

 class MyDisposable extends Object with Disposable {
   StreamController _controller = new StreamController();

   MyDisposable(Stream someStream) {
     listenToStream(someStream, (_) => print('some stream'));
     manageStreamController(_controller);
   }

   Future<Null> onDispose() {
     // Other cleanup
   }
 }

The getManagedDisposer helper allows you to clean up arbitrary objects on dispose so that you can avoid keeping track of them yourself. To use it, simply provide a callback that returns a Future of any kind. For example:

 class MyDisposable extends Object with Disposable {
   StreamController _controller = new StreamController();

   MyDisposable() {
     var thing = new ThingThatRequiresCleanup();
     getManagedDisposer(() {
       thing.cleanUp();
       return new Future(() {});
     });
   }
 }

Cleanup will then be automatically performed when the parent object is disposed. If returning a future is inconvenient or otherwise undesirable, you may also return null explicitly.

Implementing the onDispose method is entirely optional and is only necessary if there is cleanup required that is not covered by one of the helpers.

It is possible to schedule a callback to be called after the object is disposed for purposes of further, external, cleanup or bookkeeping (for example, you might want to remove any objects that are disposed from a cache). To do this, use the didDispose future:

 var myDisposable = new MyDisposable();
 myDisposable.didDispose.then((_) {
   // External cleanup
 });

Below is an example of using the class as a concrete proxy.

 class MyLifecycleThing implements DisposableManager {
   Disposable _disposable = new Disposable();

   MyLifecycleThing() {
     _disposable.manageStreamSubscription(someStream.listen(() => null));
   }

   @override
   void manageStreamSubscription(StreamSubscription sub) {
     _disposable.manageStreamSubscription(sub);
   }

   // ...more methods

   Future<Null> unload() async {
     await _disposable.dispose();
   }
 }

In this case, we want MyLifecycleThing to have its own lifecycle without explicit reference to Disposable. To do this, we use composition to include the Disposable machinery without changing the public interface of our class or polluting its lifecycle.

Implemented types

Constructors

Disposable()

Properties

didDispose Future<Null>
A Future that will complete when this object has been disposed.
no setteroverride
disposableTypeName String
A type name, similar to runtimeType but intended to work with minified code.
no setteroverride
disposalTreeSize int
The total size of the disposal tree rooted at the current Disposable instance.
no setteroverride
hashCode int
The hash code for this object.
no setterinherited
isDisposed bool
Whether this object has been disposed.
no setteroverride
isLeakFlagSet bool
Whether the leak flag for this object has been set.
no setteroverride
isOrWillBeDisposed bool
Whether the disposal of this object has been requested, is in progress, or is complete.
no setteroverride
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

awaitBeforeDispose<T>(Future<T> future) Future<T>
Add future to a list of futures that will be awaited before the object is disposed.
override
dispose() Future<Null>
Dispose of the object, cleaning up to prevent memory leaks.
override
flagLeak([String? description]) → void
Flag the object as having been disposed in a way that allows easier profiling.
override
getManagedDelayedFuture<T>(Duration duration, T callback()) Future<T>
Creates a Future that will complete, with the value returned by callback, after the given amount of time has elapsed.
override
getManagedDisposer(Disposer disposer) ManagedDisposer
Automatically handle arbitrary disposals using a callback.
override
getManagedPeriodicTimer(Duration duration, void callback(Timer timer)) Timer
Creates a periodic Timer that will be cancelled if active upon disposal.
override
getManagedTimer(Duration duration, void callback()) Timer
Creates a Timer instance that will be cancelled if active upon disposal.
override
listenToStream<T>(Stream<T> stream, void onData(T event), {Function? onError, void onDone()?, bool? cancelOnError}) StreamSubscription<T>
Returns a StreamSubscription which handles events from the stream using the provided onData, onError and onDone handlers.
override
manageAndReturnTypedDisposable<T extends Disposable>(T disposable) → T
Automatically dispose another object when this object is disposed.
override
manageCompleter<T>(Completer<T> completer) Completer<T>
Ensure that a completer is completed when the object is disposed.
override
manageDisposable(Disposable disposable) → void
override
manageStreamController(StreamController controller) → void
Automatically cancel a stream controller when this object is disposed.
override
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
onDispose() Future<Null>
Callback to allow arbitrary cleanup on dispose.
override
onWillDispose() Future<Null>
Callback to allow arbitrary cleanup as soon as disposal is requested (i.e. dispose is called) but prior to disposal actually starting.
override
subscribeToDocumentEvent(String event, EventListener callback, {bool? useCapture, EventTarget? documentObject}) → void
Adds an event listener to the document object and removes the event listener upon disposal.
subscribeToDomElementEvent(Element element, String event, EventListener callback, {bool? useCapture}) → void
Adds an event listener to the element object and removes the event listener upon disposal.
subscribeToWindowEvent(String event, EventListener callback, {bool? useCapture, EventTarget? windowObject}) → void
Adds an event listener to the window object and removes the event listener upon disposal.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Methods

disableDebugMode() → void
Disables logging enabled by enableDebugMode.
override
enableDebugMode({bool? disableLogging, bool? disableTelemetry}) → void
Causes messages to be logged for various lifecycle and management events.
override

Constants

leakFlagFactoryName → const String
The name of the factory function added to the window that produces disposable_common.LeakFlag objects when called (with a single argument: a String description).