package link.roadio.riff.ui /** * One bounded mailbox for Binder text. Only offer may run off-main; lifecycle and ticks are on-main. * AI-INTENT: sample at fixed intervals, never debounce arrivals or enqueue each message on the UI. * https://wiki.271.pics/Riff/LATEST/main-screen-status-line#player-presentation-cadence */ internal class IndexerStatusSampler( private val schedule: (Runnable, Long) -> Unit, private val cancel: (Runnable) -> Unit, private val display: (String) -> Unit, ) : AutoCloseable { private val gate = Any() private var pending: String? = null private var closed = false private var started = false private var displayed = "" private val tick = object : Runnable { override fun run() { val latest = synchronized(gate) { if (closed) return pending.also { pending = null } } if (latest != null && latest != displayed) { displayed = latest display(latest) } // Start from actual presentation, so a stalled Looper never catches up in a burst. synchronized(gate) { if (!closed) schedule(this, INTERVAL_MILLIS) } } } fun start() { if (started || closed) return started = true schedule(tick, INTERVAL_MILLIS) } fun offer(message: String) { synchronized(gate) { if (!closed) pending = message } } override fun close() { synchronized(gate) { closed = true pending = null } cancel(tick) } private companion object { const val INTERVAL_MILLIS = 1_000L } }