Skip to content

Instantly share code, notes, and snippets.

@Takhion
Created November 22, 2019 17:55
Show Gist options
  • Save Takhion/9d2a4be0334e0640205d9129b0b25c1b to your computer and use it in GitHub Desktop.
Save Takhion/9d2a4be0334e0640205d9129b0b25c1b to your computer and use it in GitHub Desktop.
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