Skip to content

viewModelScope.launch {...} not executed again when exception occurred #249

Open
@PhilippNowak96

Description

@PhilippNowak96

If you use viewModelScope.launch {} with a CoroutineExceptionHandler and an exception occurs, the same function does not run anymore when triggered again.

Repro

class AppViewModel : ViewModel() {
    private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
        Logger.e("Exception caught", throwable)
    }
    fun doSomething() {
        Logger.i("Trying to do something...")

        viewModelScope.launch(exceptionHandler) {
            Logger.i("I did it!")

            throw Exception()
        }
    }
}

(Logger is from implementation("co.touchlab:kermit:2.0.0-RC5"))

The doSomething function is triggered on compose button click. First run outputs as expected:

Trying to do something...
I did it!
Exception caught
java.lang.Exception
	at AppViewModel$doSomething$1.invokeSuspend(AppViewModel.kt:16)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        [...]

If you then click the button again, only Trying to do something... appears, so the viewModelScope.launch is not executed anymore.

If you change the doSomething() function to use CoroutineScope directly, everything works as expected:

fun doSomething() {
    Logger.i("Trying to do something...")
    CoroutineScope(Dispatchers.Main).launch(exceptionHandler) {
        Logger.i("I did it!")
        throw Exception()
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions