MVP模式内存泄漏问题

Presenter层耗时操作,例如网络请求
如果P层持有Activity的强引用,网络请求结束前Activity销毁了,会导致P层一直持有Activity的引用,使Activity无法被回收,发生内存泄漏

解决办法:

abstract class BasePresenter {
    //使用弱引用
    protected var mViewRef: Reference? = null

    fun attachView(view: T) {
        mViewRef = WeakReference(view)
    }

    fun detachView() {
        if (mViewRef != null) {
            mViewRef?.clear()
            mViewRef = null
        }
    }

    fun getView(): T? {
        return mViewRef?.get()
    }

    fun isViewAttached(): Boolean {
        return mViewRef != null && mViewRef?.get() != null
    }
}
//设置一个MVPBaseActivity
abstract class MVPBaseActivity>: AppCompatActivity() {
    protected var mPresenter:T? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mPresenter = createPresenter()
        mPresenter?.attachView(this as V)
    }

    abstract fun createPresenter(): T?

    override fun onDestroy() {
        super.onDestroy()
        mPresenter?.detachView()
    }
}

你可能感兴趣的:(MVP模式内存泄漏问题)