Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coroutine callback when running job is longer than 10 seconds

this is weird when coroutine itself was born to reduce callback

well, i didn't found any related questions, but please mention here if any

let's say i have this code

lifecycleScope.launch {
    hitApi()
}

i would like to have a callback when method hitApi() is taking longer than 10 seconds, so the activity would call some action like

onHitApiLongerThanTenSeconds() {
    showToast("hit api is taking longer than expected")
}

so... is it possible?

i know there's measureTimeMillis method but the value is returned after the job is done, cmiiw.

thanks in advance

[edit]

i don't want hitApi method is cancelled when the callback was called, just continue the process until i got the response or reach general maximum timeout like 30s or 60s

like image 534
nashihu Avatar asked Oct 28 '25 03:10

nashihu


1 Answers

Maybe this would work (didn't test):

    lifecycleScope.launch {
        supervisorScope { // or coroutineScope
            val toastJob = launch {
                delay(10000L)
                showToast("hit api is taking longer than expected")
            }
            hitApi()
            toastJob.cancel()
        }
    }
like image 182
Tenfour04 Avatar answered Oct 30 '25 12:10

Tenfour04



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!