All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.github.insanusmokrassar.TelegramBotAPI.utils.extensions.Executes.kt Maven / Gradle / Ivy

There is a newer version: 0.28.3
Show newest version
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
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy