commonMain.com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.Executes.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of TelegramBotAPI-metadata Show documentation
Show all versions of TelegramBotAPI-metadata Show documentation
This project just include all subproject of TelegramBotAPI
package com.github.insanusmokrassar.TelegramBotAPI.utils.extensions
import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor
import com.github.insanusmokrassar.TelegramBotAPI.bot.exceptions.RequestException
import com.github.insanusmokrassar.TelegramBotAPI.requests.abstracts.Request
import com.github.insanusmokrassar.TelegramBotAPI.types.Response
import kotlinx.coroutines.*
fun RequestsExecutor.executeAsync(
request: Request,
onFail: (suspend (Response) -> Unit)? = null,
scope: CoroutineScope = GlobalScope,
onSuccess: (suspend (T) -> Unit)? = null
): Job {
return scope.launch {
try {
val result = execute(request)
onSuccess ?.invoke(result)
} catch (e: RequestException) {
onFail ?.invoke(e.response)
}
}
}
fun RequestsExecutor.executeAsync(
request: Request,
scope: CoroutineScope = GlobalScope
): Deferred {
return scope.async { execute(request) }
}
suspend fun RequestsExecutor.executeUnsafe(
request: Request,
retries: Int = 0,
retriesDelay: Long = 1000L
): T? {
var leftRetries = retries
do {
try {
return execute(request)
} catch (e: RequestException) {
leftRetries--
delay(retriesDelay)
}
} while(leftRetries >= 0)
return null
}