Why does my coroutine in ViewModel not restart automatically after process death, and how should I handle re-subscribing to state flows?
0

In my Android app using Jetpack components, I have a ViewModel where I collect data from a Flow (exposed from a repository that fetches remote + local data). This works perfectly during configuration changes, but after process death, my Flow collectors are not automatically restarted, and the UI remains blank unless I trigger an action manually.

Here’s a simplified version of my ViewModel:

@HiltViewModel
class UserViewModel @Inject constructor(
    private val userRepository: UserRepository,
    savedStateHandle: SavedStateHandle
) : ViewModel() {

    val uiState = MutableStateFlow<UserUiState>(UserUiState.Loading)

    init {
        viewModelScope.launch {
            userRepository.getUserDataFlow()
                .catch { emit(UserUiState.Error(it)) }
                .collect { data ->
                    uiState.value = UserUiState.Success(data)
                }
        }
    }
}

 

 

lifecycleScope.launchWhenStarted {
    viewModel.uiState.collect { state ->
        render(state)
    }
}

 

After process death (e.g., in the background for a while, then reopened), collect inside the ViewModel doesn’t seem to be re-triggered automatically. The UI stays in the Loading state.

My questions:

  1. Why doesn’t the coroutine in init restart after process death?

  2. Should I move this collection logic outside of init and into a function triggered by the Fragment?

  3. How should I handle re-subscribing to a Flow that needs to survive process death?

  4. Is it a good idea to persist the last UI state using SavedStateHandle or should I reload from the repository?

Looking for clean and production-ready strategies used in large-scale apps.


Anonymous May 13, 2025 20:20 60 views

0 Answers

No answers yet. Be the first to post an answer!
You need to sign in to post an answer.
Need More Help?

Get personalized assistance with your technical questions.