From 8b63ed7fa9eff5ccf279103f4038c1b954b72fa1 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Tue, 3 Dec 2024 09:38:23 +0600 Subject: [PATCH] improvements in CombinedSubcontextInitialAction --- .../CombinedSubcontextInitialAction.kt | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/tgbotapi.behaviour_builder/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/behaviour_builder/CombinedSubcontextInitialAction.kt b/tgbotapi.behaviour_builder/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/behaviour_builder/CombinedSubcontextInitialAction.kt index b4b4ae66a1..80e8ba413d 100644 --- a/tgbotapi.behaviour_builder/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/behaviour_builder/CombinedSubcontextInitialAction.kt +++ b/tgbotapi.behaviour_builder/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/behaviour_builder/CombinedSubcontextInitialAction.kt @@ -6,6 +6,13 @@ import dev.inmo.tgbotapi.types.update.abstracts.Update /** * Contains [SubAction]s which will be used in [subcontextInitialAction] in order they has been passed in [subactions]. + * + * Its [subcontextInitialAction] will iterate over incoming [subactions] until all will be completed successfully OR + * none will be successful during round of running: + * + * * Run all + * * Exclude from current running successful items + * * Do again if there are some items to run */ class CombinedSubcontextInitialAction( val subactions: List, @@ -25,14 +32,30 @@ class CombinedSubcontextInitialAction( } } val subcontextInitialAction: CustomBehaviourContextAndTypeReceiver = { update -> - subactions.forEach { subaction -> - with(subaction) { - runCatching { - invoke(update) - }.onFailure { - logger.error("Unable to execute $subaction for update $update", it) + val leftSubActions = subactions.toMutableSet() + val successSubActions = mutableSetOf() + while (leftSubActions.isNotEmpty()) { + leftSubActions.forEach { subaction -> + with(subaction) { + runCatching { + invoke(update) + }.onFailure { + logger.error(it) { + "Unable to execute $subaction for update $update. Will try on next round" + } + }.onSuccess { + successSubActions.add(subaction) + } } } + leftSubActions.removeAll(successSubActions) + if (successSubActions.isEmpty()) { + logger.error { + "Some SubActions have been unable to complete successfully:${leftSubActions.joinToString("\n") { it.toString() }}" + } + break + } + successSubActions.clear() } } }