Presenter层耗时操作,例如网络请求
如果P层持有Activity的强引用,网络请求结束前Activity销毁了,会导致P层一直持有Activity的引用,使Activity无法被回收,发生内存泄漏
解决办法:
abstract class BasePresenter<T> {
//使用弱引用
protected var mViewRef: Reference<T>? = null
fun attachView(view: T) {
mViewRef = WeakReference<T>(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<V,T:BasePresenter<V>>: 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()
}
}