diff --git a/app/src/main/java/com/androiddevs/lerun/utils/ViewBindingUtils.kt b/app/src/main/java/com/androiddevs/lerun/utils/ViewBindingUtils.kt index edd3a3e..d671d7c 100644 --- a/app/src/main/java/com/androiddevs/lerun/utils/ViewBindingUtils.kt +++ b/app/src/main/java/com/androiddevs/lerun/utils/ViewBindingUtils.kt @@ -36,3 +36,43 @@ fun Fragment.viewBinding(factory: (View) -> T): ReadOnlyProper binding = null } } + + +/* +class FragmentViewBindingDelegate( + val fragment: Fragment, + val viewBindingFactory: (View) -> T +) : ReadOnlyProperty { + private var _binding: T? = null + + init { + fragment.lifecycle.addObserver(object : DefaultLifecycleObserver { + override fun onCreate(owner: LifecycleOwner) { + fragment.viewLifecycleOwnerLiveData.observe(fragment) { viewLifecycleOwner -> + viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver { + override fun onDestroy(owner: LifecycleOwner) { + _binding = null + } + }) + } + } + }) + } + + override fun getValue(thisRef: Fragment, property: KProperty<*>): T { + val binding = _binding + if (binding != null) { + return binding + } + + val lifecycle = fragment.viewLifecycleOwner.lifecycle + if (!lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) { + throw IllegalStateException("Should not attempt to get bindings when Fragment views are destroyed.") + } + + return viewBindingFactory(thisRef.requireView()).also { _binding = it } + } +} + +fun Fragment.viewBinding(viewBindingFactory: (View) -> T) = + FragmentViewBindingDelegate(this, viewBindingFactory)*/