
ru.hnau.jutils.finisher.PossibleFinishersList.kt Maven / Gradle / Ivy
package ru.hnau.jutils.finisher
import ru.hnau.jutils.possible.*
import java.util.*
fun List>>.onlySuccess(): Finisher> =
Finisher { onFinished ->
if (isEmpty()) {
onFinished.invoke(emptyList())
return@Finisher
}
var notFinishedCount = size
val result = LinkedList()
val decAndReturnIfNeed = {
notFinishedCount--
if (notFinishedCount <= 0) {
onFinished.invoke(result)
}
}
forEach {
it.await(
onSuccess = { finisherResult ->
synchronized(result) {
result.add(finisherResult)
decAndReturnIfNeed.invoke()
}
},
onError = {
synchronized(result) {
decAndReturnIfNeed.invoke()
}
}
)
}
}
fun List>>.allSuccess(): Finisher>> =
Finisher { onFinished ->
if (isEmpty()) {
onFinished.success(emptyList())
return@Finisher
}
val result = LinkedList()
forEach {
it.await(
onSuccess = { finisherResult ->
synchronized(result) {
result.add(finisherResult)
if (result.size >= size) {
onFinished.success(result)
}
}
},
onError = onFinished::errorOrUndefined
)
}
}
fun List>>>.flattenIfAllSuccess(): Finisher>> =
allSuccess().map { possibleListOfLists -> possibleListOfLists.map { it.flatten() } }
fun List>>>.flattenOfSuccess(): Finisher> =
all().map { data -> data.mapNotNull { it.data }.flatten() }
fun List>>.firstSuccess(): Finisher> =
Finisher { onFinished ->
if (isEmpty()) {
onFinished.undefined()
return@Finisher
}
val locker = Object()
var firstError: Exception? = null
var errorsCount = 0
forEach {
it.await(
onSuccess = onFinished::success,
onError = {ex ->
synchronized(locker) {
firstError = firstError ?: ex
errorsCount++
if (errorsCount >= size) {
onFinished.error(firstError)
}
}
}
)
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy