music: move automatic reloading to musikr

This commit is contained in:
Alexander Capehart
2025-01-01 13:08:53 -07:00
parent ef751f1a11
commit 68098b97ed
5 changed files with 95 additions and 84 deletions
@@ -0,0 +1,42 @@
package org.oxycblt.musikr.track
import android.content.Context
import android.database.ContentObserver
import android.os.Handler
import android.os.Looper
import org.oxycblt.musikr.fs.MusicLocation
internal class LocationObserver(
private val context: Context,
private val location: MusicLocation,
private val listener: UpdateTracker.Callback
) : ContentObserver(Handler(Looper.getMainLooper())), Runnable {
private val handler = Handler(Looper.getMainLooper())
init {
context.applicationContext.contentResolver.registerContentObserver(
location.uri,
true,
this
)
}
fun release() {
handler.removeCallbacks(this)
context.applicationContext.contentResolver.unregisterContentObserver(this)
}
override fun onChange(selfChange: Boolean) {
// Batch rapid-fire updates into a single callback after delay
handler.removeCallbacks(this)
handler.postDelayed(this, REINDEX_DELAY_MS)
}
override fun run() {
listener.onUpdate(location)
}
private companion object {
const val REINDEX_DELAY_MS = 500L
}
}
@@ -0,0 +1,35 @@
package org.oxycblt.musikr.track
import android.content.Context
import org.oxycblt.musikr.fs.MusicLocation
interface UpdateTracker {
fun track(locations: List<MusicLocation>)
fun release()
interface Callback {
fun onUpdate(location: MusicLocation)
}
companion object {
fun from(context: Context, callback: Callback): UpdateTracker = UpdateTrackerImpl(context, callback)
}
}
private class UpdateTrackerImpl(
private val context: Context,
private val callback: UpdateTracker.Callback
) : UpdateTracker {
private val observers = mutableListOf<LocationObserver>()
override fun track(locations: List<MusicLocation>) {
release()
observers.addAll(locations.map { LocationObserver(context, it, callback) })
}
override fun release() {
observers.forEach { it.release() }
observers.clear()
}
}