Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
interface Cleanup {
fun registerForCleanup(onCleanup: () -> Unit): Closeable
}
class CloseableRefCallback<T : Cleanup>(
private val callback: T.() -> Unit
) : Closeable {
private val resourceRef = AtomicReference<Pair<T, Closeable>?>(null)
@Suppress("MemberVisibilityCanBePrivate")
var resource: T?
get() = resourceRef.get()?.first
set(newResource) {
val new = newResource?.let { it to it.registerForCleanup { this.close() } }
val old = resourceRef.getAndSet(new)
old?.second?.close()
}
override fun close() {
resource = null
}
operator fun invoke() {
resource?.callback()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.