That fuck shit the fascists are using
1package org.tm.archive.components
2
3import android.view.View
4import androidx.fragment.app.Fragment
5import androidx.lifecycle.DefaultLifecycleObserver
6import androidx.lifecycle.Lifecycle
7import androidx.lifecycle.LifecycleOwner
8import androidx.viewbinding.ViewBinding
9import kotlin.reflect.KProperty
10
11/**
12 * ViewBinderDelegate which enforces the "best practices" for maintaining a reference to a view binding given by
13 * Android official documentation.
14 */
15open class ViewBinderDelegate<T : ViewBinding>(
16 private val bindingFactory: (View) -> T,
17 private val onBindingWillBeDestroyed: (T) -> Unit = {}
18) : DefaultLifecycleObserver {
19
20 private var binding: T? = null
21
22 operator fun getValue(thisRef: Fragment, property: KProperty<*>): T {
23 if (binding == null) {
24 if (!thisRef.viewLifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) {
25 error("Invalid state to create a binding.")
26 }
27
28 thisRef.viewLifecycleOwner.lifecycle.addObserver(this@ViewBinderDelegate)
29 binding = bindingFactory(thisRef.requireView())
30 }
31
32 return binding!!
33 }
34
35 override fun onDestroy(owner: LifecycleOwner) {
36 if (binding != null) {
37 onBindingWillBeDestroyed(binding!!)
38 }
39
40 binding = null
41 }
42}