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