org.hnau.emitter.Main.kt Maven / Gradle / Ivy
package org.hnau.emitter
import kotlinx.coroutines.*
import org.hnau.base.data.Time
import org.hnau.base.data.cached.auto.AutoCachedSuspend
import org.hnau.base.data.cached.auto.auto
import org.hnau.base.data.cached.manual.suspend.cachedSuspend
import org.hnau.base.data.cached.manual.sync.cached
import org.hnau.base.data.maybe.Maybe
import org.hnau.base.data.maybe.map
import org.hnau.base.data.maybe.tryOrError
import org.hnau.base.data.now
import org.hnau.base.data.outdatable.Outdatable
import org.hnau.base.data.outdatable.ifActual
import org.hnau.base.data.toLevelsString
import org.hnau.base.extensions.boolean.checkTruth
import org.hnau.base.extensions.delay
import org.hnau.base.extensions.launch
import org.hnau.emitter.extensions.map
import org.hnau.emitter.observing.value.always.actual.ActualEmitterSimple
import org.hnau.emitter.observing.value.suitable.cached.SuitableCachedEmitterSimple
import org.hnau.emitter.utils.executors.job.JobExecutor
import java.lang.Exception
import java.lang.IllegalStateException
import java.util.concurrent.atomic.AtomicInteger
object Main {
@JvmStatic
fun main(args: Array) = runBlocking {
val started = Time.now()
val requestNumber = AtomicInteger(0)
val emitter = SuitableCachedEmitterSimple>>, suspend () -> Maybe>(
getNewContent = {
cachedSuspend>>().auto {
val number = requestNumber.incrementAndGet()
tryOrError {
log(started, "Request ($number) started")
delay(Time.SECOND * 2)
log(started, "Request ($number) finished")
if (number <= 1) {
throw IllegalStateException("Test error")
} else {
Outdatable.since(
value = "Success $number",
lifetime = Time.SECOND * 3
)
}
}
}
},
handleCachedValue = { value,
onSuitable,
onNotSuitable ->
value.checkValueExists(
ifValueNotExists = { true },
ifValueExists = {
it.checkSuccess(
ifError = { false },
ifSuccess = {
it.checkActual(
ifActual = { true },
ifOutdated = { false }
)
}
)
}
).checkTruth(
ifTrue = { onSuitable { value().map { outdatable -> outdatable.forceValue } } },
ifFalse = { onNotSuitable() }
)
}
)
attach(
started = started,
emitter = emitter,
number = 1
)
delay(Time.SECOND * 5)
//emitter.invalidateValue()
attach(
started = started,
emitter = emitter,
number = 2
)
delay(Time.SECOND * 10)
}
private fun log(
started: Time,
message: String
) {
val text = "[${(Time.now() - started).toLevelsString()}] $message"
println(text)
}
private fun attach(
started: Time,
number: Int,
emitter: Emitter Maybe>
) {
emitter.attach { lazySuspend ->
Dispatchers.IO.launch {
lazySuspend().checkSuccess(
ifSuccess = {
log(started, "[$number] Received result: $it")
},
ifError = {
log(started, "[$number] Received error: $it")
}
)
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy