Lifecycle 라이브러리는 Jetpack Compose와 통합할 수 있는 내장 API를 제공합니다. 주요 API에는 다음이 포함됩니다.
현재 Lifecycle.State의 흐름
특정 Lifecycle.Event를 기반으로 블록을 실행할 수 있도록 하는 LifecycleEffects
이러한 통합은 Compose 계층 구조 내에서 Lifecycle을 관리하는 편리한 후크를 제공합니다. 이 문서에서는 앱에서 이를 사용하는 방법을 설명합니다.
흐름을 사용하여 수명 주기 상태 수집
Lifecycle은 현재 Lifecycle.State를 Kotlin StateFlow로 제공하는 currentStateFlow 속성을 노출합니다. 이 Flow를 State로 수집할 수 있습니다. 이렇게 하면 앱이 컴포지션 중에 Lifecycle의 변경사항을 읽을 수 있습니다.
앞의 예시는 lifecycle-common 모듈을 사용하여 액세스할 수 있습니다. currentStateAsState() 메서드는 lifecycle-runtime-compose 모듈에서 사용할 수 있으며 한 줄로 현재 Lifecycle 상태를 편리하게 읽을 수 있습니다. 다음 예를 참고하세요.
특정 Lifecycle.Event가 발생할 때 블록을 실행할 수 있는 LifecycleEffects도 있습니다.
LifecycleEventEffect(Lifecycle.Event.ON_START){// do something here}
LifecycleEventEffect 외에 LifecycleStartEffect 및 LifecycleResumeEffect도 사용할 수 있습니다. 이러한 API는 특정 이벤트에 연결됩니다. 또한 이벤트가 시작되었을 수 있는 코드를 정리하는 데 도움이 되는 추가 블록을 기본 블록 내에 제공합니다.
LifecycleStartEffect
LifecycleStartEffect는 LifecycleEffect와 유사하지만 Lifecycle.Event.ON_START 이벤트에서만 실행됩니다. 다른 Compose 키처럼 작동하는 키도 허용합니다. 키가 변경되면 블록이 다시 실행됩니다.
Lifecycle.Event.ON_STOP 이벤트가 있거나 효과가 컴포지션을 종료하면 onStopOrDispose 블록이 실행됩니다. 이렇게 하면 시작 블록의 일부였던 모든 작업을 삭제할 수 있습니다.
LifecycleStartEffect{// ON_START code is executed hereonStopOrDispose{// do any needed clean up here}}
LifecycleResumeEffect
LifecycleResumeEffect는 LifecycleStartedEffect와 동일한 방식으로 작동하지만 대신 Lifecycle.Event.ON_RESUME 이벤트에서 실행됩니다. 또한 정리 작업을 실행하는 onPauseOrDispose 블록도 제공합니다.
LifecycleResumeEffect{// ON_RESUME code is executed hereonPauseOrDispose{// do any needed clean up here}}
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-27(UTC)"],[],[],null,["# Integrate Lifecycle with Compose\n\nThe Lifecycle library offers built-in APIs that let you integrate with Jetpack\n[Compose](/jetpack/compose). Key APIs include the following:\n\n- Flows for the current `Lifecycle.State`.\n- `LifecycleEffects` that lets you run a block based on a specific `Lifecycle.Event`.\n\nThese integrations provide convenient hooks to manage Lifecycles within the\nCompose hierarchy. This document outlines how you can use them in your app.\n| **Note:** The APIs described in this document were introduced in Lifecycle version 2.7.0.\n\nCollect lifecycle state with flows\n----------------------------------\n\nLifecycle exposes a `currentStateFlow` property that provides the current\n`Lifecycle.State` as a Kotlin `StateFlow`. You can collect this `Flow` as\n`State`. This allows your app to read changes in the Lifecycle during\ncomposition. \n\n val lifecycleOwner = LocalLifecycleOwner.current\n val stateFlow = lifecycleOwner.lifecycle.currentStateFlow\n ...\n val currentLifecycleState by stateFlow.collectAsState()\n\nThe preceding example is accessible using the `lifecycle-common` module. The\n`currentStateAsState()` method is available in the `lifecycle-runtime-compose`\nmodule, which lets you conveniently read the current Lifecycle state with a\nsingle line. The following example demonstrates this: \n\n val lifecycleOwner = LocalLifecycleOwner.current\n val currentLifecycleState = lifecycleOwner.lifecycle.currentStateAsState()\n\nRun code on lifecycle events\n----------------------------\n\nThere are also `LifecycleEffects` that let you run a block when a particular\n`Lifecycle.Event` occurs. \n\n LifecycleEventEffect(Lifecycle.Event.ON_START) {\n // do something here\n }\n\n| **Warning:** You cannot use this to listen for `Lifecycle.Event.ON_DESTROY` since composition ends before this signal is sent.\n\nIn addition to the `LifecycleEventEffect`, you can also use\n`LifecycleStartEffect` and `LifecycleResumeEffect`. These APIs are tied to\nspecific events. They also offer an additional block within their primary block\nthat helps clean up any code that the event might have kicked off.\n\n### LifecycleStartEffect\n\nThe `LifecycleStartEffect` is similar to the `LifecycleEffect`, but it runs only\non `Lifecycle.Event.ON_START` events. It also accepts keys that work like other\nCompose keys. When the key changes, it triggers the block to run again.\n\nWhen there is a `Lifecycle.Event.ON_STOP` event or the effect exits composition,\nit executes a `onStopOrDispose` block. This allows for the clean up of any work\nthat was part of the starting block. \n\n LifecycleStartEffect {\n // ON_START code is executed here\n\n onStopOrDispose {\n // do any needed clean up here\n }\n }\n\n| **Note:** The `onStopOrDispose` block is always required and if it is not needed, you should use the `LifecycleEffect`, passing in the `Lifecycle.Event.ON_START` event instead.\n\n### LifecycleResumeEffect\n\nThe `LifecycleResumeEffect` works in the same way as the\n`LifecycleStartedEffect`, but it executes on the `Lifecycle.Event.ON_RESUME`\nevent instead. It also provides an `onPauseOrDispose` block that performs the\nclean up. \n\n LifecycleResumeEffect {\n // ON_RESUME code is executed here\n\n onPauseOrDispose {\n // do any needed clean up here\n }\n }"]]