How to interrupt the execution of a Kotlin coroutine

Viewed 322

I have an API request and I should open new activity or show an error depends on the response.

CoroutineScope(IO).launch {
    val result = joinGameWithFriendRequest(inputSessionId)
    if (result.error == "Session id not found") {
        showToast("Session id not found")
        this.cancel() // How to stop here?
    }
    if (this.isActive)
        withContext(Dispatchers.Main) {
            val intent = Intent(this@PlayWithFriend, PlayField::class.java)
                    startActivity(intent) //todo start new Activity in a func
        }
}
            

I found a solution using cancel() and .isActive but it looks bad and if you have multiple consecutive checks, the code will be terrible. Is there some nice way to interrupt the coroutine like "return" in functions?

2 Answers

You can use CoroutineScope.ensureActive() function inside a coroutine to check if it's active:

scope.launch {
    ...
    ensureActive()
    ...
}

If scope is canceled the code after ensureActive() won't be executed.


According to your code, instead of cancelling the coroutine you can just return from the coroutine if some condition is true:

scope.launch {
    val result = joinGameWithFriendRequest(inputSessionId)
    if (result.error == "Session id not found") {
        showToast("Session id not found")
        return@launch
    }

    // the next code won't be executed if result.error == "Session id not found"
    withContext(Dispatchers.Main) {
            val intent = Intent(this@PlayWithFriend, PlayField::class.java)
                    startActivity(intent) //todo start new Activity in a func
    }
        
}

You should throw CancellationException() in order to cancel coroutine from inside coroutine.

Related