android - 如何通过 suspendCancellableCoroutine 防止使用 try catch
问题描述
我做了一个在我的交互器中调用异步方法的协同处理,问题是当继续块被执行时,我不想使用 try catch 块,因为我认为这不是正确的方法。
主持人
override fun signInWithCoroutines(email: String, password: String) {
launch {
view?.showProgress()
try{
signInInteractor.signInWithCoroutinesTest(email,password)
}catch(e FirebaseLoginException){ ---> want to know if there is another way to do this
view.showError(e.getMessage())
}
view?.hideProgress()
view?.navigateToMain()
}
}
登录交互器
override suspend fun signInWithCoroutinesTest(email: String, password: String): Unit = suspendCancellableCoroutine { continuation ->
FirebaseAuth.getInstance()?.signInWithEmailAndPassword(email, password)?.addOnCompleteListener {
if (it.isSuccessful) {
continuation.resume(Unit)
} else {
continuation.resumeWithException(FirebaseLoginException("Error while login in, try again")
}
}
}
问题
是否有另一种方法可以从我的交互者那里捕获我的演示者中的继续恢复和异常?
我读过 try catch 块是与协程一起工作的反模式
https://proandroiddev.com/kotlin-coroutines-patterns-anti-patterns-f9d12984c68e
如果异步块可能抛出异常,不要依赖于用 try/catch 块包装它。
解决方案
您没有使用async
块,因此 try catch 正是您应该用来包装方法调用的异常的suspend
方法。
推荐阅读
- javascript - 反应自定义多选不适用于外部阵列
- xml - Spring批量读取输入文件,其中包含日期和时间
- java - java - 如何将ffmpeg的输出通过管道传输到java中的ffplay?
- javascript - React 热键无法访问更新状态
- vue.js - 在vue js中有条件地绑定一个指令
- java - 杰克逊反序列化具有换行符的 Xml 元素作为 Java POJO 的值
- c++ - 访问 i+1 时出现无效向量下标错误
- c++ - 为什么我的函数代码中有一个模棱两可的地方,它计算十进制 n 的二进制表示中 1 的数量
- python - 为什么 gettext 会自动给我错误的翻译?
- swift - 无法分配给属性:“lowerBound”是一个“let”常量——在 UIView 中变为 let