package com.xyj.checkupgrade.extend
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
//定义一个DSL风格的LifecycleObserver
class LifecycleObserverKt(listenerBuilder: ListenerBuilder.() -> Unit) : LifecycleObserver {
private val mListener: ListenerBuilder = ListenerBuilder().also(listenerBuilder)
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() = mListener.mCreateAction?.invoke()
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() = mListener.mStartAction?.invoke()
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() = mListener.mResumeAction?.invoke()
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() = mListener.mPauseAction?.invoke()
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() = mListener.mStopAction?.invoke()
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() = mListener.mDestroyAction?.invoke()
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onAny() = mListener.mAnyAction?.invoke()
inner class ListenerBuilder {
internal var mPauseAction: (() -> Unit)? = null
internal var mStartAction: (() -> Unit)? = null
internal var mStopAction: (() -> Unit)? = null
internal var mCreateAction: (() -> Unit)? = null
internal var mDestroyAction: (() -> Unit)? = null
internal var mResumeAction: (() -> Unit)? = null
internal var mAnyAction: (() -> Unit)? = null
fun onAny(action: () -> Unit) {
mAnyAction = action
}
fun onCreate(action: () -> Unit) {
mCreateAction = action
}
fun onStart(action: () -> Unit) {
mStartAction = action
}
fun onResume(action: () -> Unit) {
mResumeAction = action
}
fun onPause(action: () -> Unit) {
mPauseAction = action
}
fun onStop(action: () -> Unit) {
mStopAction = action
}
fun onDestroy(action: () -> Unit) {
mDestroyAction = action
}
}
}
复制代码
使用方法:
//启动一个可以监听activity生命周期并且自动取消的协程
fun AppCompatActivity.launchWithLifecycle(block: suspend CoroutineScope.() -> Unit) {
val job = CoroutineScope(Dispatchers.Main).launch {
block()
}
lifecycle.addObserver(LifecycleObserverKt{
onDestroy {
job.cancel()
}
})
}
复制代码