
ru.hnau.jutils.producer.CachingProducer.kt Maven / Gradle / Ivy
package ru.hnau.jutils.producer
import ru.hnau.jutils.TimeValue
import ru.hnau.jutils.handle
import ru.hnau.jutils.helpers.*
abstract class CachingProducer(
private val valueLifetime: TimeValue? = null
) : Producer() {
private var isObserving = false
private var cachedValue: Outdatable? = null
protected abstract fun getNewValue(): T
protected fun update(newValue: T?) {
synchronized(this) {
cachedValue = newValue?.toOutdatable(valueLifetime)
newValue?.let(this::call)
}
}
protected fun clear() =
update(null)
protected fun invalidate() = synchronized(this) {
val newValue = if (isObserving) getNewValue() else null
update(newValue)
}
override fun onAttached(listener: (T) -> Unit) {
super.onAttached(listener)
synchronized(this) {
cachedValue?.value?.let {
listener.invoke(it)
return@synchronized
}
invalidate()
}
}
override fun onIsObservingChanged(isObserving: Boolean) {
super.onIsObservingChanged(isObserving)
this.isObserving = isObserving
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy