Why does my Kotlin Android app crash when using coroutines in ViewModel?

Hello

I am developing an Android app in Kotlin and recently added coroutines to handle background tasks in my ViewModel. :slightly_smiling_face: The issue is that when the screen rotates or the activity is recreated; the app sometimes crashes with JobCancellationException / other lifecycle-related errors.:upside_down_face:

I expected the ViewModel scope to manage this automatically but it seems like my coroutines are still being cancelled unexpectedly.:thinking:

I tried using viewModelScope.launch as recommended & also tested with lifecycleScope, but I am not sure which one is the best practice when making network calls that should survive configuration changes.:thinking:

I also considered using rememberCoroutineScope in Compose but the problem persists there as well. It’s a bit confusing because the coroutine documentation shows multiple scopes & I am not clear on which one is safe for long-running tasks.:slightly_smiling_face: I recently read about tools like Cursor AI helping developers debug coroutine issues; which made me think if there’s a similar approach for Android ViewModels.:innocent:

Has anyone faced this issue and found a clean solution? Should I be using something like repeatOnLifecycle or a different pattern to avoid crashes?

A step-by-step explanation or code snippet would really help clarify how coroutines should be structured inside a ViewModel for Android apps.

Thank you !!:slightly_smiling_face:

How are you getting your view model in the view?

You could use a try catch and logs to see which coroutine is blocking the main thread, remember that they are asynchronous