commonMain.jetbrains.datalore.base.async.SimpleAsync.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.async
import jetbrains.datalore.base.function.Consumer
import jetbrains.datalore.base.observable.event.ListenerCaller
import jetbrains.datalore.base.observable.event.Listeners
import jetbrains.datalore.base.registration.Registration
class SimpleAsync : ResolvableAsync {
private var mySuccessItem: ItemT? = null
private var mySucceeded = false
private var myFailureThrowable: Throwable? = null
private var myFailed = false
private var mySuccessHandlers: Listeners>? = Listeners()
private var myFailureHandlers: Listeners>? = Listeners()
override fun onSuccess(successHandler: Consumer): Registration {
if (alreadyHandled()) {
if (mySucceeded) {
successHandler(mySuccessItem!!)
}
return Registration.EMPTY
}
return mySuccessHandlers!!.add(successHandler)
}
override fun onResult(successHandler: Consumer, failureHandler: Consumer): Registration {
val successRegistration = onSuccess(successHandler)
val failureRegistration = onFailure(failureHandler)
return object : Registration() {
override fun doRemove() {
successRegistration.remove()
failureRegistration.remove()
}
}
}
override fun onFailure(failureHandler: Consumer): Registration {
if (alreadyHandled()) {
if (myFailed) {
failureHandler(myFailureThrowable!!)
}
return Registration.EMPTY
}
return myFailureHandlers!!.add(failureHandler)
}
override fun map(success: (ItemT) -> ResultT): Async {
return Asyncs.map(this, success, SimpleAsync())
}
override fun flatMap(success: (ItemT) -> Async?): Async {
return Asyncs.select(this, success, SimpleAsync())
}
override fun success(result: ItemT) {
if (alreadyHandled()) {
throw IllegalStateException("Async already completed")
}
mySuccessItem = result
mySucceeded = true
mySuccessHandlers!!.fire(object : ListenerCaller> {
override fun call(l: Consumer) {
@Suppress("UNCHECKED_CAST")
l(mySuccessItem as ItemT)
}
})
clearHandlers()
}
override fun failure(t: Throwable) {
if (alreadyHandled()) {
throw IllegalStateException("Async already completed")
}
myFailureThrowable = t
myFailed = true
myFailureHandlers!!.fire(object : ListenerCaller> {
override fun call(l: Consumer) {
l(myFailureThrowable!!)
}
})
clearHandlers()
}
private fun clearHandlers() {
mySuccessHandlers = null
myFailureHandlers = null
}
private fun alreadyHandled(): Boolean {
return mySucceeded || myFailed
}
internal fun hasSucceeded(): Boolean {
return mySucceeded
}
internal fun hasFailed(): Boolean {
return myFailed
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy