package link.roadio.riff.player.library import java.util.concurrent.Executor /** Coalesces invalidations on a worker; only the currently accepted snapshot may reach its owner. */ internal class LatestSnapshotLoader( private val worker: Executor, private val receiver: Executor, private val load: (K) -> V, private val isCurrent: (K) -> Boolean, private val receive: (K, Result) -> Unit, ) { private var pending: K? = null private var running = false fun request(key: K) { synchronized(this) { pending = key if (running) return running = true } worker.execute { while (true) { val next = synchronized(this) { val key = pending pending = null if (key == null) running = false key } ?: break val result = runCatching { load(next) } receiver.execute { if (isCurrent(next)) receive(next, result) } } } } }