首页 > 解决方案 > 运行作业超过 10 秒时的协程回调

问题描述

当协程本身为减少回调而生时,这很奇怪

好吧,我没有找到任何相关的问题,但如果有的话,请在这里提及

假设我有这个代码

lifecycleScope.launch {
    hitApi()
}

hitApi()当方法花费的时间超过 10 秒时,我想有一个回调,所以活动会调用一些动作,比如

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

所以……有可能吗?

我知道有measureTimeMillis方法,但工作完成后返回值,cmiiw。

提前致谢

[编辑]

我不希望hitApi在调用回调时取消方法,只需继续该过程直到我得到响应或达到一般最大超时时间,如 30 秒或 60 秒

标签: kotlinkotlin-coroutines

解决方案


也许这会起作用(没有测试):

    lifecycleScope.launch {
        supervisorScope { // or coroutineScope
            val toastJob = launch {
                delay(10000L)
                showToast("hit api is taking longer than expected")
            }
            hitApi()
            toastJob.cancel()
        }
    }

推荐阅读