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

org.hnau.emitter.observing.content.combine.FunnelEmitter.kt Maven / Gradle / Ivy

package org.hnau.emitter.observing.content.combine

import org.hnau.base.extensions.it
import org.hnau.emitter.Emitter


class FunnelEmitter private constructor(
        private val sources: List>,
        initialEmitterPosition: Int
) : CombineEmitter(
        dependencies = sources
) {

    companion object {

        fun  create(
                sources: Iterable>,
                initialEmitterPosition: Int = 0
        ): FunnelEmitter {
            val list = sources.map(::it)
            check(list.isNotEmpty()) { "Sources must not be empty" }
            check(initialEmitterPosition >= 0) { "InitialEmitterPosition must not be less than zero" }
            check(initialEmitterPosition < list.size) { "InitialEmitterPosition must be less than sources count" }
            return FunnelEmitter(
                    sources = sources.map(::it),
                    initialEmitterPosition = initialEmitterPosition
            )
        }
    }

    private var currentEmitterPosition = initialEmitterPosition

    override val value get() = sources[currentEmitterPosition].value

    override fun onDependencyChanged(position: Int) {
        super.onDependencyChanged(position)
        currentEmitterPosition = position
        call()
    }

}

fun  Iterable>.funnel(
        initialEmitterPosition: Int = 0
): Emitter = FunnelEmitter.create(
        sources = this,
        initialEmitterPosition = initialEmitterPosition
)




© 2015 - 2025 Weber Informatics LLC | Privacy Policy