lifecycle的简单实用

MVP模式中,我们的presenter可能需要在activity销毁的时候释放一些资源

通常我们会这么写

    override fun onDestroy() {
        super.onDestroy()
        presenter.destory():
    }

如果有很多个类或者自定义的view都需要在activity销毁的额时候释放,可能会造成onDestroy方法很臃肿。
而使用lifecycle可以很方便的监听activity的生命周期,从而在presenter内部资源,而不需要外部调用presenter.destory():方法

使用非常简单:

presenter集成LifecycleObserver

public class MainPresenter implements LifecycleObserver {

    public MainPresenter() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void onResume(){
        Log.i("LHD", "onResume onResume onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onDestroy() {
        Log.i("LHD", "onDestroy onDestroy onDestroy");
    }
}

以下是activity代码,(kotlin)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        presenter = MainPresenter()
        //将实现了LifecycleObserver接口的presenter传递给lifecycle即可
        lifecycle.addObserver(presenter)
}

只要这样,presenter就能监听到activity的生命周期啦。

如图:
lifecycle

还可以监听其它生命周期方法:

    public enum Event {
        /**
         * Constant for onCreate event of the {@link LifecycleOwner}.
         */
        ON_CREATE,
        /**
         * Constant for onStart event of the {@link LifecycleOwner}.
         */
        ON_START,
        /**
         * Constant for onResume event of the {@link LifecycleOwner}.
         */
        ON_RESUME,
        /**
         * Constant for onPause event of the {@link LifecycleOwner}.
         */
        ON_PAUSE,
        /**
         * Constant for onStop event of the {@link LifecycleOwner}.
         */
        ON_STOP,
        /**
         * Constant for onDestroy event of the {@link LifecycleOwner}.
         */
        ON_DESTROY,
        /**
         * An {@link Event Event} constant that can be used to match all events.
         */
        ON_ANY
    }

以上就是lifecycle的简单使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值