首页 > 解决方案 > 如何通过 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 块包装它。

标签: androidkotlincoroutinekotlin-coroutinesandroid-mvp

解决方案


您没有使用async块,因此 try catch 正是您应该用来包装方法调用的异常的suspend方法。


推荐阅读