Created
May 12, 2020 12:52
-
-
Save marcellogalhardo/4f9d209a93975b70c309464441ffc18e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package com.marcellogalhardo.weak | |
import java.lang.ref.WeakReference | |
import kotlin.properties.ReadWriteProperty | |
import kotlin.reflect.KProperty | |
/** | |
* Creates a new instance of the [WeakDelegate] for better Kotlin | |
* syntax using the [referent] parameter as an initial reference. | |
* | |
* Note the GC might reclaim the [referent] value before your first usage. | |
*/ | |
fun <T> weak(referent: T? = null): ReadWriteProperty<Any, T?> = WeakDelegate(referent) | |
/** | |
* Represents a [WeakReference] value - which do not prevent their referents | |
* from being made finalizable, finalized, and then reclaimed. | |
*/ | |
private class WeakDelegate<T>( | |
private var weakReference: WeakReference<T?>? | |
) : ReadWriteProperty<Any, T?> { | |
constructor(value: T) : this(WeakReference(value)) | |
override operator fun getValue( | |
thisRef: Any, | |
property: KProperty<*> | |
): T? = weakReference?.get() | |
override 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