ru.hnau.jutils.producer.locked_producer.LockedProducersContainer.kt Maven / Gradle / Ivy
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))