Search code examples
androidkotlincoroutinekotlin-coroutinesandroid-mvp

How to prevent the usage of try catch with suspendCancellableCoroutine


I have made a corouting that calls an asynchronous method in my interactor, the thing is that when the continuation block gets executed, I dont want to use a try catch block since I think is not the right way to do this.

Presenter

  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()
        }

    }

SignInInteractor

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")
            }
        }
    }

Question

Is there another way to catch the continuation resume and the exception in my presenter from my interactor ?

I have readed that the try catch block is an anti pattern to work with coroutines

https://proandroiddev.com/kotlin-coroutines-patterns-anti-patterns-f9d12984c68e

If async block may throw exception don’t rely on wrapping it with try/catch block.


Solution

  • You're not using an async block, so try catch is exactly what you should be using to wrap exceptions called by a suspend method.