定义一个DSL风格的LifecycleObserver(Kotlin)

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()
        }
    })
}
复制代码

转载于:https://juejin.im/post/5cf7491bf265da1bb7765771

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值