publicinterfaceDefaultLifecycleObserver : LifecycleObserver { /** * Notifies that `ON_CREATE` event occurred. * * * This method will be called after the [LifecycleOwner]'s `onCreate` * method returns. * * @param owner the component, whose state was changed */ publicfunonCreate(owner: LifecycleOwner) {}
/** * Notifies that `ON_START` event occurred. * * * This method will be called after the [LifecycleOwner]'s `onStart` method returns. * * @param owner the component, whose state was changed */ publicfunonStart(owner: LifecycleOwner) {}
/** * Notifies that `ON_RESUME` event occurred. * * * This method will be called after the [LifecycleOwner]'s `onResume` * method returns. * * @param owner the component, whose state was changed */ publicfunonResume(owner: LifecycleOwner) {}
/** * Notifies that `ON_PAUSE` event occurred. * * * This method will be called before the [LifecycleOwner]'s `onPause` method * is called. * * @param owner the component, whose state was changed */ publicfunonPause(owner: LifecycleOwner) {}
/** * Notifies that `ON_STOP` event occurred. * * * This method will be called before the [LifecycleOwner]'s `onStop` method * is called. * * @param owner the component, whose state was changed */ publicfunonStop(owner: LifecycleOwner) {}
/** * Notifies that `ON_DESTROY` event occurred. * * * This method will be called before the [LifecycleOwner]'s `onDestroy` method * is called. * * @param owner the component, whose state was changed */ publicfunonDestroy(owner: LifecycleOwner) {} }
publicfuninterface LifecycleEventObserver : LifecycleObserver { /** * Called when a state transition event happens. * * @param source The source of the event * @param event The event */ publicfunonStateChanged(source: LifecycleOwner, event: Lifecycle.Event) }
publicinterfaceLifecycleOwner { /** * Returns the Lifecycle of the provider. * * @return The lifecycle of the provider. */ publicval lifecycle: Lifecycle }
overridefunaddObserver(observer: LifecycleObserver) { enforceMainThreadIfNeeded("addObserver") val initialState = if (state == State.DESTROYED) State.DESTROYED else State.INITIALIZED val statefulObserver = ObserverWithState(observer, initialState) val previous = observerMap.putIfAbsent(observer, statefulObserver) if (previous != null) { return } val lifecycleOwner = lifecycleOwner.get() ?: // it is null we should be destroyed. Fallback quickly return val isReentrance = addingObserverCounter != 0 || handlingEvent var targetState = calculateTargetState(observer) addingObserverCounter++ while (statefulObserver.state < targetState && observerMap.contains(observer) ) { pushParentState(statefulObserver.state) val event = Event.upFrom(statefulObserver.state) ?: throw IllegalStateException("no event up from ${statefulObserver.state}") statefulObserver.dispatchEvent(lifecycleOwner, event) popParentState() // mState / subling may have been changed recalculate targetState = calculateTargetState(observer) } if (!isReentrance) { // we do sync only on the top level. sync() } addingObserverCounter-- }
privatefunsync() { val lifecycleOwner = lifecycleOwner.get() ?: throw IllegalStateException( "LifecycleOwner of this LifecycleRegistry is already " + "garbage collected. It is too late to change lifecycle state." ) while (!isSynced) { newEventOccurred = false if (state < observerMap.eldest()!!.value.state) { backwardPass(lifecycleOwner) } val newest = observerMap.newest() if (!newEventOccurred && newest != null && state > newest.value.state) { forwardPass(lifecycleOwner) } } newEventOccurred = false }
overridevar currentState: State get() = state /** * Moves the Lifecycle to the given state and dispatches necessary events to the observers. * * @param state new state */ set(state) { enforceMainThreadIfNeeded("setCurrentState") moveToState(state) }
privatefunmoveToState(next: State) { if (state == next) { return } check(!(state == State.INITIALIZED && next == State.DESTROYED)) { "no event down from $state in component ${lifecycleOwner.get()}" } state = next if (handlingEvent || addingObserverCounter != 0) { newEventOccurred = true // we will figure out what to do on upper level. return } handlingEvent = true sync() handlingEvent = false if (state == State.DESTROYED) { observerMap = FastSafeIterableMap() } }
publicfunlifecycleEventObserver(`object`: Any): LifecycleEventObserver { val isLifecycleEventObserver = `object` is LifecycleEventObserver val isDefaultLifecycleObserver = `object` is DefaultLifecycleObserver if (isLifecycleEventObserver && isDefaultLifecycleObserver) { return DefaultLifecycleObserverAdapter( `object` as DefaultLifecycleObserver, `object` as LifecycleEventObserver ) } if (isDefaultLifecycleObserver) { return DefaultLifecycleObserverAdapter(`object` as DefaultLifecycleObserver, null) } if (isLifecycleEventObserver) { return `object` as LifecycleEventObserver } val klass: Class<*> = `object`.javaClass val type = getObserverConstructorType(klass) if (type == GENERATED_CALLBACK) { val constructors = classToAdapters[klass]!! if (constructors.size == 1) { val generatedAdapter = createGeneratedAdapter( constructors[0], `object` ) return SingleGeneratedAdapterObserver(generatedAdapter) } val adapters: Array<GeneratedAdapter> = Array(constructors.size) { i -> createGeneratedAdapter(constructors[i], `object`) } return CompositeGeneratedAdaptersObserver(adapters) } return ReflectiveGenericLifecycleObserver(`object`) }
/** * Sets the current state and notifies the observers. * * Note that if the `currentState` is the same state as the last call to this method, * calling this method has no effect. * * @param event The event that was received */ openfunhandleLifecycleEvent(event: Event) { enforceMainThreadIfNeeded("handleLifecycleEvent") moveToState(event.targetState) }
funinjectIfNeededIn(activity: Activity) { if (Build.VERSION.SDK_INT >= 29) { // On API 29+, we can register for the correct Lifecycle callbacks directly LifecycleCallbacks.registerIn(activity) } // Prior to API 29 and to maintain compatibility with older versions of // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and // need to support activities that don't extend from FragmentActivity from support lib), // use a framework fragment to get the correct timing of Lifecycle events val manager = activity.fragmentManager if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(ReportFragment(), REPORT_FRAGMENT_TAG).commit() // Hopefully, we are the first to make a transaction. manager.executePendingTransactions() } }
overridefunonDestroy() { super.onDestroy() dispatch(Lifecycle.Event.ON_DESTROY) // just want to be sure that we won't leak reference to an activity processListener = null }
privatefundispatch(event: Lifecycle.Event) { if (Build.VERSION.SDK_INT < 29) { // Only dispatch events from ReportFragment on API levels prior // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks // added in ReportFragment.injectIfNeededIn dispatch(activity, event) } }
internalfundispatch(activity: Activity, event: Lifecycle.Event) { if (activity is LifecycleRegistryOwner) { activity.lifecycle.handleLifecycleEvent(event) return } if (activity is LifecycleOwner) { val lifecycle = (activity as LifecycleOwner).lifecycle if (lifecycle is LifecycleRegistry) { lifecycle.handleLifecycleEvent(event) } } }
funinjectIfNeededIn(activity: Activity) { if (Build.VERSION.SDK_INT >= 29) { // On API 29+, we can register for the correct Lifecycle callbacks directly LifecycleCallbacks.registerIn(activity) } // ... }
publicFragment() { initLifecycle(); } privatevoidinitLifecycle() { mLifecycleRegistry = newLifecycleRegistry(this); mSavedStateRegistryController = SavedStateRegistryController.create(this); // The default factory depends on the SavedStateRegistry so it // needs to be reset when the SavedStateRegistry is reset mDefaultFactory = null; if (!mOnPreAttachedListeners.contains(mSavedStateAttachListener)) { registerOnPreAttachListener(mSavedStateAttachListener); } }
voidperformCreate(Bundle savedInstanceState) { mChildFragmentManager.noteStateNotSaved(); mState = CREATED; mCalled = false; mLifecycleRegistry.addObserver(newLifecycleEventObserver() { @Override publicvoidonStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) { if (event == Lifecycle.Event.ON_STOP) { if (mView != null) { mView.cancelPendingInputEvents(); } } } }); onCreate(savedInstanceState); mIsCreated = true; if (!mCalled) { thrownewSuperNotCalledException("Fragment " + this + " did not call through to super.onCreate()"); } mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
voidperformStart() { mChildFragmentManager.noteStateNotSaved(); mChildFragmentManager.execPendingActions(true); mState = STARTED; mCalled = false; onStart(); if (!mCalled) { thrownewSuperNotCalledException("Fragment " + this + " did not call through to super.onStart()"); } mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); if (mView != null) { mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START); } mChildFragmentManager.dispatchStart(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
voidperformResume() { mChildFragmentManager.noteStateNotSaved(); mChildFragmentManager.execPendingActions(true); mState = RESUMED; mCalled = false; onResume(); if (!mCalled) { thrownewSuperNotCalledException("Fragment " + this + " did not call through to super.onResume()"); } mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); if (mView != null) { mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); } mChildFragmentManager.dispatchResume(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
voidperformPause() { mChildFragmentManager.dispatchPause(); if (mView != null) { mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE); } mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE); mState = AWAITING_ENTER_EFFECTS; mCalled = false; onPause(); if (!mCalled) { thrownewSuperNotCalledException("Fragment " + this + " did not call through to super.onPause()"); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
voidperformStop() { mChildFragmentManager.dispatchStop(); if (mView != null) { mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_STOP); } mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP); mState = ACTIVITY_CREATED; mCalled = false; onStop(); if (!mCalled) { thrownewSuperNotCalledException("Fragment " + this + " did not call through to super.onStop()"); } }
1 2 3 4 5 6 7 8 9 10 11 12
voidperformDestroy() { mChildFragmentManager.dispatchDestroy(); mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY); mState = ATTACHED; mCalled = false; mIsCreated = false; onDestroy(); if (!mCalled) { thrownewSuperNotCalledException("Fragment " + this + " did not call through to super.onDestroy()"); } }