Skip to content

Instantly share code, notes, and snippets.

@jamiesanson
Last active February 19, 2018 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiesanson/e0ae7f746c22382ec68f455138087eae to your computer and use it in GitHub Desktop.
Save jamiesanson/e0ae7f746c22382ec68f455138087eae to your computer and use it in GitHub Desktop.
Kotlin Lifecycle-aware fields
import android.arch.lifecycle.*
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import kotlin.reflect.KProperty
fun <T> Fragment.selfClearing(valInitializer: (() -> T)? = null) = LifecycleDelegate(this.lifecycle, valInitializer)
fun <T> AppCompatActivity.selfClearing(valInitializer: (() -> T)? = null) = LifecycleDelegate(this.lifecycle, valInitializer)
class LifecycleDelegate<T>(
lifecycle: Lifecycle,
private val initializer: (() -> T)? = null
): LifecycleObserver {
private var value: Any = EMPTY
private var initializerInvoked = false
private var withinLifecycle = false
private object EMPTY
init {
lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
withinLifecycle = true
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
withinLifecycle = false
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
if (!withinLifecycle) return null
if (value == EMPTY) {
if (!initializerInvoked && initializer != null) {
value = initializer.invoke()!!
initializerInvoked = true
@Suppress("UNCHECKED_CAST")
return value as T
}
}
@Suppress("UNCHECKED_CAST")
return value as T
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
if (withinLifecycle && value != null) {
this.value = value
}
}
}
class TestActivity: AppCompatActivity() {
var testString: String? by selfClearing()
override fun onCreate() {
super.onCreate()
testString = "Test"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment