액티비티의 상태에 따라 처리되는 코드를 쉽게 관리할 수 있게 도와주는 라이브러리이다.
LifecycleOwner는 Activity를 의미하고, 내부에 Lifecycle을 갖고 있습니다. (ComponentActivity 상속받고 있고 이 안에 getLifecycle() 함수가 구현되어 있다.) Lifecycle은 액티비티의 상태를 저장하고 옵저버들에게 상태변화를 알려준다.
Lifecycle 상태를 알고 싶다면 LifecycleObserver를 생성하고 Lifecycle에 등록을 하면 된다.
Lifecycle의 상태를 받고 싶으면 Observer를 먼저 구현해야 한다.
아래와 같이 MyObserver.kt파일을 생성하고 DefaultLifecycleObserver를 상속한 MyObserver를 구현했다.
class MyObserver : DefaultLifecycleObserver {
companion object {
const val TAG = "MyObersever"
}
override fun onCreate(owner: LifecycleOwner) {
Log.d(TAG, "OnCreated")
}
}
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
Activity는 lifecycle 객체를 직접 참조할 수 있다. 옵저버를 생성할 때 인자로 lifecycle을 넘겨준다. lifecycle을 전달해주면 옵저버에서 lifecycle에 접근하여 현재 상태를 알 수 있다.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val observer = MyObserver()
lifecycle.addObserver(observer)
}
}
내부적으로 액티비티의 상태가 변경되면 Lifecycle로 전달되고 Lifecycle은 옵저버들에게 상태를 알려준다.
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
동적으로 Lifecycle의 상태를 알아야 할 때도 있다. lifeCycle.currentState로 현재상태를 알 수 있다. 옵저버에서 사용한 코드 State.isAtLeast는 상태를 점수로 표현하고 현재의 위치가 어떤 상태보다 큰지 boolean으로 리턴해주는 함수이다. STARTED는 DESTROYED, INITIALIZED, CREATED 보다 큰 값을 갖고 있다. 만약 STARTED 이상의 상태에서만 초기화가 필요하다면 State.isAtLeast를 사용하여 구현할 수 있다.
@SuppressWarnings("WeakerAccess")
public enum State {
/**
* Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
* any more events. For instance, for an {@link android.app.Activity}, this state is reached
* <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
*/
DESTROYED,
/**
* Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
* the state when it is constructed but has not received
* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
*/
INITIALIZED,
/**
* Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
* </ul>
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onStart() onStart} call;
* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
* </ul>
*/
STARTED,
/**
* Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached after {@link android.app.Activity#onResume() onResume} is called.
*/
RESUMED;
/**
* Compares if this State is greater or equal to the given {@code state}.
*
* @param state State to compare with
* @return true if this State is greater or equal to the given {@code state}
*/
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
위의 이벤트(Event)와 상태(State)의 관계를 그래프로 표현한 그림이다. 각각의 상태에 따라 어떤 이벤트가 전달되는지 알려준다.