launchWhenLifecycleEventDestroy<T> method

Future<T> launchWhenLifecycleEventDestroy<T>({
  1. bool runWithDelayed = false,
  2. Cancellable? cancellable,
  3. required FutureOr<T> block(
    1. Cancellable cancellable
    ),
})

Implementation

Future<T> launchWhenLifecycleEventDestroy<T>(
    {bool runWithDelayed = false,
    Cancellable? cancellable,
    required FutureOr<T> Function(Cancellable cancellable) block}) {
  Completer<T> completer = runWithDelayed ? Completer() : Completer.sync();
  final observer = LifecycleObserver.eventDestroy(() {
    if (!completer.isCompleted && cancellable?.isUnavailable != true) {
      if (runWithDelayed) {
        completer.complete(Future(() => block(cancellable ?? Cancellable())));
      } else {
        completer.complete(block(cancellable ?? Cancellable()));
      }
    }
  });
  addLifecycleObserver(observer);

  cancellable?.onCancel
      .then((value) => removeLifecycleObserver(observer, fullCycle: false));
  return completer.future;
}