1 package com.android.systemui.util
2 
3 import java.lang.ref.SoftReference
4 import java.lang.ref.WeakReference
5 import java.util.concurrent.atomic.AtomicReference
6 import kotlin.properties.ReadWriteProperty
7 import kotlin.reflect.KProperty
8 
9 /**
10  * Creates a Kotlin idiomatic weak reference.
11  *
12  * Usage:
13  * ```
14  * var weakReferenceObj: Object? by weakReference(null)
15  * weakReferenceObj = Object()
16  * ```
17  */
weakReferencenull18 fun <T> weakReference(obj: T? = null): ReadWriteProperty<Any?, T?> {
19     return object : ReadWriteProperty<Any?, T?> {
20         var weakRef = WeakReference<T?>(obj)
21         override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
22             return weakRef.get()
23         }
24 
25         override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
26             weakRef = WeakReference(value)
27         }
28     }
29 }
30 
31 /**
32  * Creates a Kotlin idiomatic soft reference.
33  *
34  * Usage:
35  * ```
36  * var softReferenceObj: Object? by softReference(null)
37  * softReferenceObj = Object()
38  * ```
39  */
softReferencenull40 fun <T> softReference(obj: T? = null): ReadWriteProperty<Any?, T?> {
41     return object : ReadWriteProperty<Any?, T?> {
42         var softRef = SoftReference<T?>(obj)
43         override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
44             return softRef.get()
45         }
46 
47         override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
48             softRef = SoftReference(value)
49         }
50     }
51 }
52 
53 /**
54  * Creates a nullable Kotlin idiomatic [AtomicReference].
55  *
56  * Usage:
57  * ```
58  * var atomicReferenceObj: Object? by nullableAtomicReference(null)
59  * atomicReferenceObj = Object()
60  * ```
61  */
nullableAtomicReferencenull62 fun <T> nullableAtomicReference(obj: T? = null): ReadWriteProperty<Any?, T?> {
63     return object : ReadWriteProperty<Any?, T?> {
64         val t = AtomicReference(obj)
65         override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
66             return t.get()
67         }
68 
69         override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
70             t.set(value)
71         }
72     }
73 }
74