Search code examples
androidkotlinandroid-jetpack-composeandroid-viewmodel

Closing application using `activity. Finish()` causes malfunction on restart


I am using activity. Finish() to close an application on logout. However, when the application is opened back up again, my coroutines do not launch, more specifically, a viewModelScope.launch does not fire up. Could this because I am closing the application wrong? I would like to close the application and clear all viewModels and data from the application on logout

Here is how I am closing the application

val activity = (LocalContext.current as? Activity)
activity?. Finish()

Here is the coroutine that fails to launch on restart (user login)

fun login() {
    Log.d("Login test", "Attempt to login stage 1")
    viewModelScope.launch {
        Log.d("Collection test", "Attempt to login stage 2")
        userState = AuthResource.Loading
        try {
            
        } catch (e: IOException) {
           
        } catch (e: HttpException) {
            
        } 
    }

}

The first log message is received, but never the second one and the loading state is never activated. I am using kotlin with jetpack compose


Solution

  • When an Activity finishes, the associated view model is terminated. Coroutines that haven't run yet won't be run. That's part of the point of a viewModel- it's bound to a lifecycle, and that lifecycle ends with the Activity. You need to run it on another scope if you want to ensure it happens.