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

org.hnau.emitter.extensions.EmitterToAlwaysEmitterExtensions.kt Maven / Gradle / Ivy

There is a newer version: 2.1.3
Show newest version
package org.hnau.emitter.extensions

import org.hnau.base.data.possible.lateinit.Lateinit
import org.hnau.base.data.possible.lateinit.sync
import org.hnau.base.data.possible.lateinit.synchronized
import org.hnau.base.extensions.it
import org.hnau.base.utils.safe.SafeContext
import org.hnau.base.utils.safe.synchronized
import org.hnau.emitter.Detacher
import org.hnau.emitter.Emitter
import org.hnau.emitter.observing.push.always.AlwaysEmitter


fun  Emitter.makeAlways(
        ifNoValue: () -> T
) = object : AlwaysEmitter() {

    private val sourceValue = Lateinit.synchronized()

    override val value: T
        get() = sourceValue.checkPossible(
                ifValueExists = ::it,
                ifValueNotExists = ifNoValue
        )

    private var detacher: Detacher? = null
        set(value) = synchronized(this) {
            field?.detach()
            field = value
        }

    override fun beforeFirstAttached() {
        super.beforeFirstAttached()
        detacher = [email protected] { newSourceValue ->
            sourceValue.set(newSourceValue)
            onChanged()
        }
    }

    override fun afterLastDetached() {
        super.afterLastDetached()
        detacher = null
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy