Created
January 20, 2022 09:11
-
-
Save kibotu/ecf38c96d496e197afc4a210ae896880 to your computer and use it in GitHub Desktop.
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