Compose에서 안전하게 Activity 찾기

Donggi Hong·2022년 11월 29일
2
/**
 * Find the closest Activity in a given Context.
 */
internal fun Context.findActivity(): Activity {
    var context = this
    while (context is ContextWrapper) {
        if (context is Activity) return context
        context = context.baseContext
    }
    throw IllegalStateException("Permissions should be called in the context of an Activity")
}

google/accompanist에서 사용하는 함수입니다.

context에서 반복하여 activity를 검색합니다.
정말 없을 떄에는 throw를 하기에, 대부분의 정상적인 상황에서 activity를 찾을 수 있습니다.

이 함수를 이용해서 얻을 수 있는 장점은 아래와 같습니다.

  1. 기존 LocalContext.current as Activity에서 종종 발생하던 TypeCastException을 방지할 수 있습니다.
  2. 변수 초기화 시 context가 존재하지 않아도, 호출 시에만 존재한다면 정상적으로 activity를 가져올 수 있습니다.
profile
꿈 많은 응애 안드로이드 개발자

0개의 댓글