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 java.lang.ref.WeakReference | |
import kotlin.reflect.KProperty | |
inline fun <reified T> weak() = WeakReferenceDelegate<T>() | |
inline fun <reified T> weak(value: T) = WeakReferenceDelegate(value) | |
/** | |
* e.g. var x by weak<Context?>(activity) | |
*/ | |
class WeakReferenceDelegate<T> { | |
private var weakReference: WeakReference<T>? = null | |
constructor() | |
constructor(value: T) { | |
weakReference = WeakReference(value) | |
} | |
operator fun getValue(thisRef: Any, property: KProperty<*>): T? = weakReference?.get() | |
operator fun setValue(thisRef: Any, property: KProperty<*>, value: T) { | |
weakReference = WeakReference(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment