Created
November 22, 2019 17:55
-
-
Save Takhion/9d2a4be0334e0640205d9129b0b25c1b to your computer and use it in GitHub Desktop.
Revisions
-
Takhion created this gist
Nov 22, 2019 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,27 @@ 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() } }