Last active
February 19, 2018 03:41
-
-
Save jamiesanson/e0ae7f746c22382ec68f455138087eae to your computer and use it in GitHub Desktop.
Kotlin Lifecycle-aware fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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