Reputation: 11
Detect cancellation from CoroutineScope
I am trying to detect cancellation from CoroutineScope, but isCancelled property doesn't change when I trying to call cancel method inside CoroutineScope
Method I expected to cancel the Coroutine from ViewModel
fun login() = viewModelScope.launch{
try{
repository.login(emailLogin.get()!!, passwordLogin.get()!!)
}catch (e: AuthenticationHttpErrorException){
cancel(CancellationException(e.message))
Toast.makeText(getApplication(),e.message, Toast.LENGTH_SHORT).show()
Log.e("ERROR LOGIN", e.message)
}
}
How I called the login method from Activity
fun submitLogin(view: View){
val loginResult = authenticationViewModel.login()
if(loginResult.isCancelled){
Log.e("LOGIN FAILED", "Login cancelled")
}else{
Log.v("LOGIN SUCCESS", "Login success")
}
}
I am expecting isCancelled property change to true, when I called cancel method from CoroutineScope and Trigger some code inside if statement
Upvotes: 1
Views: 3060
Reputation: 8371
You are canceling it on the catch
block. Which means that
repository.login(emailLogin.get()!!, passwordLogin.get()!!)
does not throw any exception. Or if it does, perhaps it is not the AuthenticationHttpErrorException
that is being thrown. Just to check the error that is happening, try catching a general Exception
and than handle the coroutine the same.So:
catch (e: Exception)
Upvotes: 0
Reputation: 6258
launch
does start an asynchronous coroutine. Therefore the login
-body will run later and you can't access the result directly after the invocation.
In your example a simple suspend
function may be better.
Upvotes: 1