commonMain.jetbrains.datalore.base.observable.event.EventSources.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of lets-plot-common Show documentation
Show all versions of lets-plot-common Show documentation
Lets-Plot JVM package without rendering part
/*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.base.observable.event
import jetbrains.datalore.base.function.Predicate
import jetbrains.datalore.base.observable.collections.CollectionAdapter
import jetbrains.datalore.base.observable.collections.CollectionItemEvent
import jetbrains.datalore.base.observable.collections.list.ObservableList
import jetbrains.datalore.base.registration.Registration
object EventSources {
/**
* Event source which always dispatched the same events on subscription. It's useful for testing and
* composition. In Rx-like libraries a similar thing is called cold observable.
*/
fun of(vararg events: EventT): EventSource {
return object : EventSource {
override fun addHandler(handler: EventHandler): Registration {
for (e in events) {
handler.onEvent(e)
}
return Registration.EMPTY
}
}
}
fun empty(): EventSource {
return composite()
}
fun composite(vararg sources: EventSource): EventSource {
return CompositeEventSource(*sources)
}
fun composite(sources: Iterable>): EventSource {
return CompositeEventSource(sources)
}
fun filter(source: EventSource, pred: Predicate): EventSource {
return object : EventSource {
override fun addHandler(handler: EventHandler): Registration {
return source.addHandler(object : EventHandler {
override fun onEvent(event: EventT) {
if (pred(event)) {
handler.onEvent(event)
}
}
})
}
}
}
fun map(src: EventSource, f: (SourceEventT) -> TargetEventT): EventSource {
return MappingEventSource(src, f)
}
fun selectList(
list: ObservableList, selector: (ItemT?) -> EventSource): EventSource {
return object : EventSource {
override fun addHandler(handler: EventHandler): Registration {
val itemRegs = ArrayList()
for (item in list) {
itemRegs.add(selector(item).addHandler(handler))
}
val listReg = list.addListener(object : CollectionAdapter() {
override fun onItemAdded(event: CollectionItemEvent) {
itemRegs.add(event.index, selector(event.newItem).addHandler(handler))
}
override fun onItemRemoved(event: CollectionItemEvent) {
itemRegs.removeAt(event.index).remove()
}
})
return object : Registration() {
override fun doRemove() {
for (r in itemRegs) {
r.remove()
}
listReg.remove()
}
}
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy