All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.org.brightify.hyperdrive.property.impl.CollectedObservableProperty.kt Maven / Gradle / Ivy

There is a newer version: 0.1.159
Show newest version
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)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy