CompositionLocal LocalLifecycleOwner not present

권대원
5 min readMay 16, 2024

--

Photo by Rob Wicks on Unsplash

이전 글에서 android.lifecycle:lifecycle-*:2.7.0 버전대에서 겪은 일들을 소개했었습니다.

이번 글에서는 android.lifecycle:lifecycle-*:2.8.0 버전대에서 겪었던 이슈들을 소개해보려 합니다.

당시 lifecycle-runtime-compose:2.8.0-alpha03, androidx.compose.ui:ui-android:1.7.0-alpha03 를 사용중이었습니다.(사실 버전을 alpha로 올린건 LifecycleResumeEffect 변경사항에 대응하기 위함이었습니다)

그러던 중 LocalLifecycleOwner를 사용하는 곳에서 아래와 같은 에러를 내뱉기 시작했습니다.

java.lang.IllegalStateException: CompositionLocal LocalLifecycleOwner not present
at androidx.lifecycle.compose.LocalLifecycleOwnerKt$LocalLifecycleOwner$1.invoke(LocalLifecycleOwner.kt:26)
at androidx.lifecycle.compose.LocalLifecycleOwnerKt$LocalLifecycleOwner$1.invoke(LocalLifecycleOwner.kt:25)
at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
at androidx.compose.runtime.LazyValueHolder.getCurrent(ValueHolders.kt:29)
at androidx.compose.runtime.LazyValueHolder.getValue(ValueHolders.kt:31)
at androidx.compose.runtime.CompositionLocalMapKt.read(CompositionLocalMap.kt:90)
at androidx.compose.runtime.ComposerImpl.consume(Composer.kt:2135)
at androidx.lifecycle.compose.FlowExtKt.collectAsStateWithLifecycle(FlowExt.kt:180)

LocalLifecycleOwner 이 존재하지 않다고 하네요..?

물론 버전업을 진행하면서 아래 변경사항도 인지는 하고 있었습니다.

LocalLifecycleOwner moved from Compose UI to lifecycle-runtime-compose so that its Compose-based helper APIs can be used outside of Compose UI. Thanks Jake Wharton for the contribution.

다만, compose-ui 에서는 아직 androidx.compose.ui.platform 패키지의 LocalLifecycleOwner를 참조하고 있지만 lifecycle 에서는 androidx.lifecycle.compose 패키지에 LocalLifecycleOwner 존재하기에 호환이 되지 않는 문제였습니다.

결론은 Lifecycle 2.8.0-alpha03 을 사용하려면 최소한 Compose UI 1.7.0-alpha05 을 사용해야 한다는 것이었습니다.

라이브러리 버전간 호환은 릴리즈노트에 적어주거나 컴파일될 때 알려주면 좋지 않을까라는 생각을 하며 이슈트래커에 제보를 했습니다.

최근 2.8.0 stable 버전이 출시되면서 많은 개발자분들이 이슈를 겪고 계신거 같네요. 위 이슈에 대해 전달받은 해결방안은 아래와 같습니다.

  1. Use Compose 1.7 Beta if that is an option for you.
  2. Map androidx.compose.ui.platform.LocalLifecycleOwner (Compose 1.6) to androidx.lifecycle.compose.LocalLifecycleOwner (Lifecycle 2.8). Here's an example:
CompositionLocalProvider(
androidx.lifecycle.compose.LocalLifecycleOwner provides androidx.compose.ui.platform.LocalLifecycleOwner.current,
) {
// ...
}

3. Manually pass androidx.compose.ui.platform.LocalLifecycleOwner (Compose 1.6) to Lifecycle 2.8 methods. For instance:

val state by stateFlow.collectAsStateWithLifecycle(
owner = androidx.compose.ui.platform.LocalLifecycleOwner.current
)

아직 Lifecycle 릴리즈 노트에는 언급이 없지만, 버전간 의존성이 있다면 명시를 해주는게 좋지 않을까 하네요.

읽어주셔서 감사합니다.

--

--