Created
November 23, 2020 12:19
-
-
Save tunjid/8c6608c30366971db770e2b7a183e088 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FragmentViewBindingDelegate<T : ViewBinding>(private val factory: (View) -> T) : ReadOnlyProperty<Fragment, T> { | |
private var backingValue: T? = null | |
override operator fun getValue(thisRef: Fragment, property: KProperty<*>): T = when (val binding = backingValue) { | |
null -> { | |
thisRef.parentFragmentManager.registerFragmentLifecycleCallbacks(object : FragmentManager.FragmentLifecycleCallbacks() { | |
override fun onFragmentViewDestroyed(fm: FragmentManager, fragment: Fragment) { | |
if (fragment != thisRef) return | |
backingValue = null | |
fm.unregisterFragmentLifecycleCallbacks(this) | |
} | |
}, false) | |
factory(thisRef.requireView()).apply { backingValue = binding } | |
} | |
else -> binding | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment