commonMain.org.brightify.hyperdrive.property.impl.CollectedObservableProperty.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of runtime Show documentation
Show all versions of runtime Show documentation
Hyperdrive implementation that's needed for observations and such
package org.brightify.hyperdrive.property.impl
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import org.brightify.hyperdrive.CancellationToken
import org.brightify.hyperdrive.Lifecycle
import org.brightify.hyperdrive.property.ObservableProperty
import org.brightify.hyperdrive.property.defaultEqualityPolicy
internal class CollectedObservableProperty(
private val flow: Flow,
private val lifecycle: Lifecycle,
private val equalityPolicy: ObservableProperty.EqualityPolicy = defaultEqualityPolicy(),
initialValue: T,
): ObservableProperty {
override var value: T = initialValue
private set
private val listeners = ValueChangeListenerHandler(this)
init {
lifecycle.whileAttached {
flow.collect { newValue ->
if (equalityPolicy.isEqual(value, newValue)) { return@collect }
listeners.runNotifyingListeners(newValue) {
value = it
}
}
}
}
override fun addListener(listener: ObservableProperty.Listener): CancellationToken = listeners.addListener(listener)
override fun removeListener(listener: ObservableProperty.Listener) = listeners.removeListener(listener)
}