1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2024-06-03 00:15:27 +00:00
tgbotapi/tgbotapi.extensions.utils/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/utils/shortcuts/RequestsExecutor.kt

45 lines
1.2 KiB
Kotlin
Raw Normal View History

package dev.inmo.tgbotapi.extensions.utils.shortcuts
2020-06-02 07:39:09 +00:00
import dev.inmo.micro_utils.coroutines.safely
2020-10-04 11:06:30 +00:00
import dev.inmo.tgbotapi.bot.RequestsExecutor
import dev.inmo.tgbotapi.requests.abstracts.Request
2020-06-02 07:39:09 +00:00
import kotlinx.coroutines.*
2021-09-08 16:19:08 +00:00
import kotlin.coroutines.coroutineContext
2020-06-02 07:39:09 +00:00
fun <T: Any> RequestsExecutor.executeAsync(
request: Request<T>,
scope: CoroutineScope
): Deferred<T> = scope.async {
safely {
2020-06-02 07:39:09 +00:00
execute(request)
}
}
suspend fun <T: Any> RequestsExecutor.executeAsync(
request: Request<T>
2021-09-08 16:19:08 +00:00
): Deferred<T> = executeAsync(request, CoroutineScope(coroutineContext))
2020-06-02 07:39:09 +00:00
suspend fun <T: Any> RequestsExecutor.executeUnsafe(
request: Request<T>,
retries: Int = 0,
retriesDelay: Long = 1000L,
onAllFailed: (suspend (exceptions: Array<Throwable>) -> Unit)? = null
2020-06-02 07:39:09 +00:00
): T? {
var leftRetries = retries
val exceptions = onAllFailed ?.let { mutableListOf<Throwable>() }
2020-06-02 07:39:09 +00:00
do {
return safely (
2020-06-02 07:39:09 +00:00
{
leftRetries--
delay(retriesDelay)
exceptions ?.add(it)
null
}
) {
execute(request)
} ?: continue
} while(leftRetries >= 0)
onAllFailed ?.invoke(exceptions ?.toTypedArray() ?: emptyArray())
return null
}