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

commonMain.org.brightify.hyperdrive.property.DeferredObservableProperty.kt Maven / Gradle / Ivy

There is a newer version: 0.1.159
Show newest version
package org.brightify.hyperdrive.property

import org.brightify.hyperdrive.CancellationToken
import org.brightify.hyperdrive.utils.Optional

/**
 * This interface is an asynchronous variation to the [ObservableProperty]. Used if the initial value is undefined.
 * It doesn't provide a value if it hasn't been assigned yet, but you can block the thread until it is.
 */
public interface DeferredObservableProperty {
    /**
     * Add a [ValueChangeListener] for value change on this property.
     *
     * @return Cancellation token to cancel the listening.
     * Alternatively you can call [removeListener] with the same listener object as passed into this method.
     */
    public fun addListener(listener: Listener): CancellationToken

    /**
     * Remove a [ValueChangeListener] from listeners to value change on this property.
     */
    public fun removeListener(listener: Listener)

    /**
     * Returns the latest value if any was emitted, `null` otherwise.
     */
    public val latestValue: Optional

    /**
     * Blocks the current thread to wait for a value if [latestValue] is `null`,
     * otherwise returns [latestValue] immediately.
     *
     * Behaves identically to [nextValue] before the first value is assigned.
     */
    public suspend fun await(): T

    /**
     * Blocks the current thread until [latestValue] is replaced by a new value.
     *
     * Behaves identically to [await] before the first value is assigned.
     */
    public suspend fun nextValue(): T

    /**
     * Implemented by listeners to [DeferredObservableProperty] value changes.
     */
    public interface Listener: ValueChangeListener, T>

    public companion object {
        public fun  valueWillChange(block: Listener.(oldValue: Optional, newValue: T) -> Unit): Listener = object: Listener {
            override fun valueWillChange(oldValue: Optional, newValue: T) {
                block(oldValue, newValue)
            }
        }

        public fun  valueDidChange(block: Listener.(oldValue: Optional, newValue: T) -> Unit): Listener = object: Listener {
            override fun valueDidChange(oldValue: Optional, newValue: T) {
                block(oldValue, newValue)
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy