Last active
June 14, 2019 13:29
-
-
Save happy-bracket/8cf70d83aeda920ab375228325c795ee to your computer and use it in GitHub Desktop.
Reference Death Listener
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
object Sentries { | |
private val callbacks = ConcurrentHashMap<Reference<*>, () -> Unit>() | |
private val refs = HashSet<WeakReference<*>>() | |
private val refQueue = ReferenceQueue<Sentry<*>>() | |
private val poller = | |
Observable.interval(10000, TimeUnit.MILLISECONDS) | |
.subscribe { | |
refQueue.poll()?.let { ref -> | |
callbacks.remove(ref)?.invoke() | |
} | |
} | |
fun addSentry(sentry: Sentry<*>, onFinalize: () -> Unit) { | |
val ref = WeakReference(sentry, refQueue) | |
callbacks[ref] = onFinalize | |
refs.add(ref) | |
} | |
fun finalize() { | |
poller.dispose() | |
} | |
} | |
class Sentry<T>(entity: T) { | |
private var entityRef: T = entity | |
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = entityRef | |
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { | |
entityRef = value | |
} | |
} | |
fun <T> sentry(initValue: T, onFinalize: () -> Unit): Sentry<T> { | |
val sentry = Sentry(initValue) | |
Sentries.addSentry(sentry, onFinalize) | |
return sentry | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment