awaitBeforeDispose<T> method
Add future
to a list of futures that will be awaited before the
object is disposed.
For example, a long-running network request might use a Disposable instance when it returns. If we started to dispose while the request was pending, upon returning the request's callback would throw. We can avoid this by waiting on the request's future.
class MyDisposable extends Disposable {
MyHelper helper;
MyApi() {
helper = manageAndReturnTypedDisposable(new MyHelper());
}
Future makeRequest(String message) {
return waitBeforeDispose(
helper.sendRequest(onSuccess: (response) {
// If the `MyApi` instance was disposed while the request
// was pending, this would normally result in an exception
// being thrown. But instead, the dispose process will wait
// for the request to complete before disposing of `helper'.
helper.handleResponse(message, response);
}))
}
}
Implementation
@mustCallSuper
@override
Future<T> awaitBeforeDispose<T>(Future<T> future) {
_throwOnInvalidCall('awaitBeforeDispose', 'future', future);
_awaitableFutures.add(future);
future.then((_) {
if (!isOrWillBeDisposed) {
_awaitableFutures.remove(future);
}
}).catchError((_) {
if (!isOrWillBeDisposed) {
_awaitableFutures.remove(future);
}
});
return future;
}