From 6b9c0da6dfde6548d7ce17429faa9c5afc8459e4 Mon Sep 17 00:00:00 2001 From: Kirill Rozov Date: Thu, 1 Oct 2020 23:38:17 +0300 Subject: [PATCH] Fix access ViewBindingProperty in onDestroy() --- .../ViewBindingProperty.kt | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/vbpd/vbpd-noreflection/src/main/java/by/kirich1409/viewbindingdelegate/ViewBindingProperty.kt b/vbpd/vbpd-noreflection/src/main/java/by/kirich1409/viewbindingdelegate/ViewBindingProperty.kt index 8e92339..e70274f 100644 --- a/vbpd/vbpd-noreflection/src/main/java/by/kirich1409/viewbindingdelegate/ViewBindingProperty.kt +++ b/vbpd/vbpd-noreflection/src/main/java/by/kirich1409/viewbindingdelegate/ViewBindingProperty.kt @@ -6,6 +6,7 @@ import android.os.Handler import android.os.Looper import androidx.annotation.MainThread import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.viewbinding.ViewBinding import by.kirich1409.viewbindingdelegate.internal.checkIsMainThread @@ -25,15 +26,15 @@ public abstract class ViewBindingProperty( @MainThread public override fun getValue(thisRef: R, property: KProperty<*>): T { checkIsMainThread() - viewBinding?.let { vb -> - check(this.thisRef != null && thisRef === this.thisRef) { - "Instance of ViewBindingProperty can't be shared between classes" - } - return vb - } + viewBinding?.let { return it } this.thisRef = thisRef - getLifecycleOwner(thisRef).lifecycle.addObserver(lifecycleObserver) + val lifecycle = getLifecycleOwner(thisRef).lifecycle + if (lifecycle.currentState == Lifecycle.State.DESTROYED) { + mainHandler.post { viewBinding = null } + } else { + lifecycle.addObserver(lifecycleObserver) + } return viewBinder(thisRef).also { viewBinding = it } } @@ -44,9 +45,7 @@ public abstract class ViewBindingProperty( val thisRef = thisRef ?: return this.thisRef = null getLifecycleOwner(thisRef).lifecycle.removeObserver(lifecycleObserver) - mainHandler.post { - viewBinding = null - } + mainHandler.post { viewBinding = null } } private inner class ClearOnDestroyLifecycleObserver : DefaultLifecycleObserver {