Skip to content

Memory leak may happen #129

@initialjie

Description

@initialjie

If we reference viewBinding again in onDestroyView, this will trigger ViewBindingProperty#getValue, which will inflate another view if cache is null.

example here:

class PersonListFragment : Fragment(R.layout.fragment_person_list) {

    // Without reflection
    private val viewBinding by viewBinding(FragmentPersonListBinding::bind)

    override fun onDestroyView() {
        super.onDestroyView()
        // If we reference viewBinding again in onDestroyView, this will trigger ViewBindingProperty#getValue, which will inflate another view if cached is null
        viewBinding.xxx
    }

    inner class VBFragmentLifecycleCallback(
        fragment: Fragment,
    ) : FragmentManager.FragmentLifecycleCallbacks() {

        private val fragment by weakReference(fragment)

        override fun onFragmentViewDestroyed(
            fm: FragmentManager,
            f: Fragment,
        ) {
            // clear cache
            if (fragment === f) clear()
        }
    }
}

public open class LazyViewBindingProperty<in R : Any, T : ViewBinding>(
    private val viewBinder: (R) -> T,
) : ViewBindingProperty<R, T> {

    private var viewBinding: T? = null

    public override fun getValue(
        thisRef: R,
        property: KProperty<*>,
    ): T {
        return viewBinding ?: viewBinder(thisRef).also { viewBinding = it }
    }

    @CallSuper
    public override fun clear() {
        viewBinding = null
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions