withLifecycleEffect<T extends Object> method

T withLifecycleEffect<T extends Object>({
  1. T? data,
  2. T factory()?,
  3. Launcher<T>? launchOnFirstCreate,
  4. Launcher<T>? launchOnFirstStart,
  5. Launcher<T>? launchOnFirstResume,
  6. Launcher<T>? repeatOnStarted,
  7. Launcher<T>? repeatOnResumed,
  8. Launcher<T>? launchOnDestroy,
})

直接使用生命周期对类对象进行操作

Implementation

T withLifecycleEffect<T extends Object>({
  T? data,
  T Function()? factory,
  Launcher<T>? launchOnFirstCreate,
  Launcher<T>? launchOnFirstStart,
  Launcher<T>? launchOnFirstResume,
  Launcher<T>? repeatOnStarted,
  Launcher<T>? repeatOnResumed,
  Launcher<T>? launchOnDestroy,
}) {
  assert(currentLifecycleState > LifecycleState.destroyed,
      'Must be used before destroyed.');
  if (currentLifecycleState <= LifecycleState.destroyed) {
    throw 'Must be used before destroyed.';
  }
  assert(data != null || factory != null,
      'data and factory cannot be null at the same time');
  if (data == null && factory == null) {
    throw 'data and factory cannot be null at the same time';
  }
  T value = data ?? factory!.call();
  assert(
      value != null, 'Unable to register LifecycleEffect with null as key');
  if (launchOnFirstCreate == null &&
      launchOnFirstStart == null &&
      launchOnFirstResume == null &&
      repeatOnStarted == null &&
      repeatOnResumed == null &&
      launchOnDestroy == null) {
    return value;
  }

  Map<Object, _LauncherLifecycleObserver> _lifecycleEffectObservers =
      lifecycleExtData.putIfAbsent(
          TypedKey<Map<Object, _LauncherLifecycleObserver>>(
              _withLifecycleEffectToken),
          () => weak.WeakMap());

  _LauncherLifecycleObserver<T> observer =
      _lifecycleEffectObservers.putIfAbsent(value as Object, () {
    final o = _LauncherLifecycleObserver<T>(value, this);
    o.launchOnFirstCreate = launchOnFirstCreate;
    o.launchOnFirstStart = launchOnFirstStart;
    o.launchOnFirstResume = launchOnFirstResume;
    o.launchOnDestroy = launchOnDestroy;

    if (repeatOnStarted != null)
      o._repeatOn[LifecycleState.started] = repeatOnStarted;
    if (repeatOnResumed != null)
      o._repeatOn[LifecycleState.resumed] = repeatOnResumed;

    //加入销毁的逻辑
    lifecycle.addObserver(LifecycleObserver.eventDestroy(
        () => _lifecycleEffectObservers.remove(value)));

    addLifecycleObserver(o, fullCycle: true);
    return o;
  }) as _LauncherLifecycleObserver<T>;

  observer.launchOnDestroy = launchOnDestroy;
  if (repeatOnStarted != null)
    observer._repeatOn[LifecycleState.started] = repeatOnStarted;
  if (repeatOnResumed != null)
    observer._repeatOn[LifecycleState.resumed] = repeatOnResumed;
  return value;
}