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
相关产品推荐
相关产品推荐

