导包
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
作用
把原本写在onCreate,onStart等等回调方法的代码放到别的类中去写
举例
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
}
}
不用Lifecycles,使用这个LocationListener的情况
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
}
}
使用了Lifecycles,再去使用这个LocationListener的情况
- 实现创建一个继承自LifecycleObserver的类
class MyObserver: LifecycleObserver {
}
2.加注解比如你要在onCreate回调中去new刚刚的那个LocationListener
class MyObserver: LifecycleObserver {
private lateinit var locationListener: MyLocationListener
fun createLocationListener() {
locationListener = MyLocationListener(context) { location ->
...
}
}
}
3.把这个Observer对象添加到LifecyclerOwner中,像activity,fragment都实现了LifecycleOwner接口
class MyActivity : AppCompatActivity() {
override fun onCreate(...) {
lifecycle.addObserver(MyObserver())
}
}
End
这个架构组件大致上就是这么用,好像还挺简单的,好像又可以把Activity中的代码减少了