Memory leak in Fragment

I would like to ask may onDetatch never called for un expected reason and thus parentView may cause memory leak. Is there a possibility for that.

open class TestFragment @ContentView constructor(@LayoutRes contentLayoutId: Int) : Fragment(contentLayoutId) {
private var parentView: BaseView? = null
    get() {
        if (field == null) {
            Timber.w("$this (test) is not attached to a BaseView host.")
        }

        return field
    }

override fun onAttach(context: Context) {
    super.onAttach(context)

    if (context is BaseView) {
        parentView = context
    } else {
        error("Fragment $this needs to get hosted by a BaseView")
    }
}

override fun onDetach() {
    parentView = null
    super.onDetach()
}

fun showLoading() {
    parentView?.showLoading()
}

}

I have no idea if there are situations where onDetach() might not get called.

However, you will only have a memory leak if you are still holding onto your instance of TestFragment after such an occurrence.

1 Like