WeakRef

expect class WeakRef<T : Any>(referred: T)

A reference that does not keep its object alive, from common code.

The object that a WeakRef points to is its referent. While other code holds the referent, get returns it. After the garbage collector frees it, get returns null. Use it for caches and listeners that must not cause a memory leak.

Example

val ref = WeakRef(bitmap)
// get() returns null after the bitmap was collected.
val image = ref.get() ?: reloadBitmap()

Platform differences

TargetWeak?
JVM, Android, iOS, macOSYes, backed by the platform weak reference
JS, ES2021 and laterYes, backed by the JS WeakRef, except for strings and numbers
JS before ES2021No, it holds the referent strongly
WasmNo, it holds the referent strongly

Watch out

  • Always handle the null from get. The collector can free the referent at any time after the last strong reference is gone.

  • Where the referent is held strongly, only clear frees it. If your design needs the memory back, check isWeakSupported.

  • On JS, strings and boxed numbers are held strongly even when isWeakSupported is true. Wrap them in your own class when that matters.

Parameters

referred

the referent.

Constructors

Link copied to clipboard
expect constructor(referred: T)

Types

Link copied to clipboard
expect object Companion

Functions

Link copied to clipboard
expect fun clear()

Drops the referent now. Every later get returns null. A second call does nothing.

Link copied to clipboard
expect fun get(): T?

Returns the referent, or null after it was collected or after clear.