conventionschedule-android/app/src/main/java/com/adlerosn/brasilfurfest/helper/FixedFileObserver.kt

43 lines
1.9 KiB
Kotlin

package com.adlerosn.brasilfurfest.helper
import android.os.FileObserver
import java.io.File
import java.io.Serializable
import java.lang.ref.WeakReference
abstract class FixedFileObserver(val path: String) : Serializable {
companion object {
val observers: MutableMap<String, MutableSet<WeakReference<FixedFileObserver>>> = mutableMapOf()
private val observerSingletons: MutableMap<String, FileObserver> = mutableMapOf()
fun getObserverFor(givenPath: String): FileObserver{
val canonical = File(givenPath).canonicalPath
if(!observerSingletons.containsKey(canonical)) observerSingletons[canonical] = object : FileObserver(canonical){
override fun onEvent(event: Int, path: String?) {
synchronized(::observers) {
observers[canonical]?.apply {
removeAll { it.get() == null }
forEach {
logIfException(FixedFileObserver::class.java) {
it.get()?.onEvent(event, givenPath)
}
}
}
}
}
}
return this.observerSingletons[canonical]!!.apply { startWatching() }
}
}
private val canonicalPath = File(path).canonicalPath!!
private var watching = false
init {
getObserverFor(path)
if (observers[canonicalPath] == null) {
observers[canonicalPath] = mutableSetOf()
}
}
fun startWatching() = synchronized(::observers) { observers[canonicalPath]!!.add(WeakReference(this)) }
fun stopWatching() = synchronized(::observers) { observers[canonicalPath]?.removeAll { it.get()?.equals(this) ?: true } ?: false }
val isWatching get() = watching
abstract fun onEvent(event: Int, path: String)
}