android - 即使一个或多个操作抛出异常,如何继续多个 Kotlin Coroutines 异步操作?
问题描述
假设我有以下代码:
viewModelScope.launch(Dispatchers.IO) {
val async1 = async { throw Exception() }
val async2 = async { throw Exception() }
val async3 = async { throw Exception() }
try { async1.await() } catch (e: Exception) { /* A */ }
try { async2.await() } catch (e: Exception) { /* B */ }
try { async3.await() } catch (e: Exception) { /* C */ }
}
我对它的期望是,即使async1
抛出异常,async2
也async3
能继续运行。
但是应用程序在调用之前崩溃了await()
。
我怎么能做我例外的事情?
解决方案
viewModelScope.launch(Dispatchers.IO) {
supervisorScope {
val async1 = async { throw Exception() }
val async2 = async { throw Exception() }
val async3 = async { throw Exception() }
try { async1.await() } catch (e: Exception) { /* A */ }
try { async2.await() } catch (e: Exception) { /* B */ }
try { async3.await() } catch (e: Exception) { /* C */ }
}
}
推荐阅读
- java - Java Reactor 中嵌套 flatMaps 的好习惯是什么?
- c++ - 创建 OpenGL 对象期间的错误
- ios - Firebase 会自动加密密码吗?
- python - 为什么我的 Keras 模型在我加载后会进行训练,即使我实际上并没有提供任何新的训练数据?
- c# - 我如何升级此算法以查找第 n 个最小元素
- twitter - 实体对象中带有符号字段的推文示例
- windows - 在 macbook 上安装 Windows
- laravel - 在 2 个模型之间进行规划
- c++ - 用于 threadx RTOS 的 C++ 包装器?
- android - Android Studio 在 XML 设计模式下移动视图