先搬一下官方示例,定位功能。
internal class MyLocationListener(
private val context: Context,
private val callback: (Location) -> Unit
) {
fun start() {
// connect to system location service
}
fun stop() {
// disconnect from system location service
}
}
class MyActivity : AppCompatActivity() {
private lateinit var myLocationListener: MyLocationListener
override fun onCreate(...) {
myLocationListener = MyLocationListener(this) { location ->
// update UI
}
}
public override fun onStart() {
super.onStart()
myLocationListener.start()
// manage other components that need to respond
// to the activity lifecycle
}
public override fun onStop() {
super.onStop()
myLocationListener.stop()
// manage other components that need to respond
// to the activity lifecycle
}
}
类似的一些组件需要感知Activity/Fragment生命周期时,得像上面一样写对应回调的样板代码。
下面来看看引入LifeCycle后有什么不同,这里以MVP中Presenter为例。
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
package com.chenxuan.common.base
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import java.lang.ref.WeakReference
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)
}
简单来说Activity/Fragment实现了LifecycleOwner接口,也就是生命周期拥有者;BasePresenter实现了LifecycleObserver接口观察生命周期变更;通过lifecycle.addObserver(presenter)关联,owner生命周期发生变化时会分发到已经订阅的observer。当然我们自己的类也可以通过LifeCycleRegistry成为LifeCycleOwner。
官方示例
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
}
}
网友评论