repeatOnLifecycle<T> method

void repeatOnLifecycle<T>({
  1. LifecycleState targetState = LifecycleState.started,
  2. bool runWithDelayed = false,
  3. Cancellable? cancellable,
  4. required FutureOr<T> block(
    1. Cancellable cancellable
    ),
})

当高于某个状态时执行给定的block

Implementation

void repeatOnLifecycle<T>(
    {LifecycleState targetState = LifecycleState.started,
    bool runWithDelayed = false,
    Cancellable? cancellable,
    required FutureOr<T> Function(Cancellable cancellable) block}) {
  if (cancellable?.isUnavailable == true) return;
  Cancellable? checkable;
  final observer = LifecycleObserver.stateChange((state) async {
    if (state >= targetState &&
        (checkable == null || checkable?.isUnavailable == true)) {
      checkable = makeLiveCancellable(other: cancellable);
      try {
        if (runWithDelayed) {
          //转到下一个事件循环,可以过滤掉连续的状态变化
          await Future.delayed(Duration.zero);
        }
        if (checkable!.isUnavailable) return;
        final result = block(checkable!);
        if (result is Future<T>) {
          await Future.delayed(Duration.zero);
          if (checkable?.isAvailable == true) await result;
        }
      } catch (_) {}
    } else if (state < targetState && checkable?.isAvailable == true) {
      checkable?.cancel();
      checkable = null;
    }
  });
  addLifecycleObserver(observer, fullCycle: true);
  cancellable?.whenCancel
      .then((value) => removeLifecycleObserver(observer, fullCycle: false));
}