unload method

Future<Null> unload()

Public method to trigger the Module unload cycle.

Calls shouldUnload(), and, if that completes successfully, continues to call onUnload() on the module and all registered child modules. If unloading is rejected, this method will complete with an error. The rejection error will not be added to the didUnload lifecycle event stream.

Initiates the unload process when the module is in the loaded or suspended state. If the module is in the unloading or unloaded state a warning is logged and the method is a noop. If the module is in any other state, a StateError is thrown.

The Future values of all children unload calls will be awaited. The first child to return an error value will emit the error on the didUnload lifecycle stream. The returned Future will also resolve with this exception.

If an Exception is thrown during the call to onUnload it will be emitted on the didUnload lifecycle stream. The returned Future will also resolve with this exception.

If an error or exception is thrown during the call to the parent onUnload lifecycle method it will be emitted on the didUnload lifecycle stream. The error will also be returned by unload.

If the unload succeeds (i.e. is not canceled via onShouldUnload and is not prevented by an uncaught exception in onUnload), then this module will also be disposed. The Future returned by this method will resolve once unload and disposal have completed.

Implementation

Future<Null> unload() {
  if (isUnloaded || isUnloading) {
    return _buildNoopResponse(
        isTransitioning: isUnloading,
        methodName: 'unload',
        currentState:
            isUnloading ? LifecycleState.unloading : LifecycleState.unloaded);
  }

  if (isOrWillBeDisposed) {
    return _buildDisposedOrDisposingResponse(methodName: 'unload');
  }

  if (!(isLoaded || isLoading || isResuming || isSuspended || isSuspending)) {
    return _buildIllegalTransitionResponse(
        targetState: LifecycleState.unloaded,
        allowedStates: [
          LifecycleState.loaded,
          LifecycleState.loading,
          LifecycleState.resuming,
          LifecycleState.suspended,
          LifecycleState.suspending
        ]);
  }

  Future? pendingTransition;
  if (_transition != null && !_transition!.isCompleted) {
    pendingTransition = _transition!.future;
  }

  _previousState = _state;
  _state = LifecycleState.unloading;
  final transition = Completer<Null>();
  _transition = transition;

  var unloadAndDispose = Completer<Null>();
  unloadAndDispose.complete(transition.future.then(((_) => dispose())));
  transition
      .complete(_unload(pendingTransition?.then((value) => value as Null)));
  return unloadAndDispose.future;
}