Skip to content

Instantly share code, notes, and snippets.

@marcellogalhardo
Created May 12, 2020 12:52
Show Gist options
  • Save marcellogalhardo/4f9d209a93975b70c309464441ffc18e to your computer and use it in GitHub Desktop.
Save marcellogalhardo/4f9d209a93975b70c309464441ffc18e to your computer and use it in GitHub Desktop.
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