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

ru.hnau.jutils.producer.locked_producer.LockedProducersContainer.kt Maven / Gradle / Ivy

There is a newer version: 2.1.1
Show newest version
package ru.hnau.jutils.producer.locked_producer

import ru.hnau.jutils.producer.detacher.ProducerDetachers


class LockedProducersContainer(
        lockedProducers: Iterable
) : LockedProducer() {

    constructor(vararg lockedProducers: LockedProducer) : this(lockedProducers.asIterable())

    private val lockedProducers =
            HashMap().apply { lockedProducers.forEach { put(it, false) } }

    private val detachers = ProducerDetachers()

    private var isAttachingToProducers = false

    private fun onProducersLockedChanged() = synchronized(this) {
        if (isAttachingToProducers) {
            return@synchronized
        }
        locked = lockedProducers.values.contains(true)
    }

    override fun onFirstAttached() {
        super.onFirstAttached()
        attachToLockedProducers()
    }

    private fun attachToLockedProducers() = synchronized(this) {
        isAttachingToProducers = true
        lockedProducers.keys.forEach { lockedProducer ->
            lockedProducer.attach(detachers) { locked ->
                lockedProducers[lockedProducer] = locked
                onProducersLockedChanged()
            }
        }
        isAttachingToProducers = false
        onProducersLockedChanged()
    }

    override fun onLastDetached() {
        super.onLastDetached()
        detachers.detachAllAndClear()
    }

}

operator fun LockedProducer.plus(other: LockedProducer) =
        LockedProducersContainer(listOf(this, other))




© 2015 - 2024 Weber Informatics LLC | Privacy Policy