Jetpack架构组件上手之Lifecycles

导包

		// 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的情况
  1. 实现创建一个继承自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中的代码减少了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值