Add onWillBeDestroyed callback to ViewBinderDelegate

This commit is contained in:
Alex Hart
2022-09-28 14:45:27 -03:00
parent 0cae15b7fd
commit 9498a34293
2 changed files with 19 additions and 5 deletions

View File

@@ -11,11 +11,19 @@ import kotlin.reflect.KProperty
* ViewBinderDelegate which enforces the "best practices" for maintaining a reference to a view binding given by
* Android official documentation.
*/
class ViewBinderDelegate<T : ViewBinding>(private val bindingFactory: (View) -> T) : DefaultLifecycleObserver {
open class ViewBinderDelegate<T : ViewBinding>(
private val bindingFactory: (View) -> T,
private val onBindingWillBeDestroyed: (T) -> Unit = {}
) : DefaultLifecycleObserver {
private var binding: T? = null
private var isBindingDestroyed = false
operator fun getValue(thisRef: Fragment, property: KProperty<*>): T {
if (isBindingDestroyed) {
error("Binding has been destroyed.")
}
if (binding == null) {
thisRef.viewLifecycleOwner.lifecycle.addObserver(this@ViewBinderDelegate)
binding = bindingFactory(thisRef.requireView())
@@ -25,6 +33,11 @@ class ViewBinderDelegate<T : ViewBinding>(private val bindingFactory: (View) ->
}
override fun onDestroy(owner: LifecycleOwner) {
if (binding != null) {
onBindingWillBeDestroyed(binding!!)
}
binding = null
isBindingDestroyed = true
}
}

View File

@@ -58,7 +58,11 @@ class AddMessageDialogFragment : KeyboardEntryDialogFragment(R.layout.v2_media_a
ownerProducer = { requireActivity() }
)
private val binding by ViewBinderDelegate(V2MediaAddMessageDialogFragmentBinding::bind)
private val binding by ViewBinderDelegate(V2MediaAddMessageDialogFragmentBinding::bind, onBindingWillBeDestroyed = { binding ->
binding.content.addAMessageInput.setInlineQueryChangedListener(null)
binding.content.addAMessageInput.setMentionValidator(null)
})
private lateinit var emojiDrawerStub: Stub<MediaKeyboard>
private lateinit var inlineQueryResultsController: InlineQueryResultsController
@@ -153,9 +157,6 @@ class AddMessageDialogFragment : KeyboardEntryDialogFragment(R.layout.v2_media_a
override fun onDestroyView() {
super.onDestroyView()
disposables.dispose()
binding.content.addAMessageInput.setInlineQueryChangedListener(null)
binding.content.addAMessageInput.setMentionValidator(null)
}
private fun initializeMentions() {