Skip to content

Instantly share code, notes, and snippets.

@Takhion
Created November 22, 2019 17:55
Show Gist options
  • Select an option

  • Save Takhion/9d2a4be0334e0640205d9129b0b25c1b to your computer and use it in GitHub Desktop.

Select an option

Save Takhion/9d2a4be0334e0640205d9129b0b25c1b to your computer and use it in GitHub Desktop.

Revisions

  1. Takhion created this gist Nov 22, 2019.
    27 changes: 27 additions & 0 deletions CloseableRefCallback.kt
    Original 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()
    }
    }