You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中withTimeout超时后如何发送TIMEOUT_ERROR至errorLiveData?

解决方案

方式一:使用withTimeoutOrNull(推荐)

withTimeoutOrNull会在超时后返回null,正常执行完逻辑则返回代码块的结果,无需处理异常,风格更简洁:

viewModelScope.launch(Dispatchers.IO) {
    val executionResult = withTimeoutOrNull(60000L) {
        repeat(10) {
            // 你的业务逻辑
        }
        // 正常完成时返回非null值,这里用Unit占位,也可以返回实际业务结果
        Unit
    }

    // 结果为null说明超时触发
    if (executionResult == null) {
        errorLiveData.postValue(TIMEOUT_ERROR)
    }
}

方式二:捕获TimeoutCancellationException

如果坚持用withTimeout,可以直接捕获它抛出的TimeoutCancellationException来处理超时逻辑:

viewModelScope.launch(Dispatchers.IO) {
    try {
        withTimeout(60000L) {
            repeat(10) {
                // 你的业务逻辑
            }
        }
    } catch (timeoutEx: TimeoutCancellationException) {
        errorLiveData.postValue(TIMEOUT_ERROR)
    }
}

两种方式都能满足需求,第一种无需异常捕获,代码更清爽,是更优雅的实现方式。

内容的提问来源于stack exchange,提问作者Andrey Kijonok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:42:02