为什么要使用Lifecycle?
有时候我们的很多操作和生命周期是相关联的,就好比我们如果用mvp架构,Presenter如何感知Activity或者Fragment的生命周期?可能会想到这样做: IPresenter中定义和生命周期相关的几个方法,然后在MainActivity中调用对应的方法。可以是可以,但是这样做会有个问题:在MainActivity中的每个生命周期方法中都要调用一次IPresenter中的接口,很不灵性。所以Lifecycle就诞生了。
如何使用Lifecycle?
IPresenter实现LifecycleObserver接口
interface IPresenter : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(@NotNull owner: LifecycleOwner)
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy(@NotNull owner: LifecycleOwner)
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onLifecycleChanged(@NotNull owner: LifecycleOwner, @NotNull event: Lifecycle.Event)
}
BasePresenter在对应的生命周期处理View
abstract class BasePresenter<V : IView>(view: IView) : IPresenter {
@Suppress("UNCHECKED_CAST")
protected var mViewRef: WeakReference<V>? = WeakReference(view as V)
override fun onCreate(owner: LifecycleOwner) {
}
override fun onDestroy(owner: LifecycleOwner) {
mViewRef?.clear()
}
override fun onLifecycleChanged(owner: LifecycleOwner, event: Lifecycle.Event) {
}
}
BaseActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter = createPresenter()
lifecycle.addObserver(presenter)
}
最后贴一下官方样例
class MyActivity : Activity(), LifecycleOwner {
private lateinit var lifecycleRegistry: LifecycleRegistry
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleRegistry = LifecycleRegistry(this)
lifecycleRegistry.markState(Lifecycle.State.CREATED)
}
public override fun onStart() {
super.onStart()
lifecycleRegistry.markState(Lifecycle.State.STARTED)
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
}
总结一下
Activity/Fragment实现了LifecycleOwner接口,也就是成为了生命周期拥有者;BasePresenter实现了LifecycleObserver接口,观察生命周期变化;通过lifecycle.addObserver(presenter)相关联,owner生命周期发生变化时会分发到已经订阅的observer。当然我们自己的类也可以通过LifeCycleRegistry成为LifeCycleOwner。