Why does my coroutine in ViewModel not restart automatically after process death, and how should I handle re-subscribing to state flows?
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:
-
Why doesn’t the coroutine in
init
restart after process death? -
Should I move this collection logic outside of
init
and into a function triggered by the Fragment? -
How should I handle re-subscribing to a
Flow
that needs to survive process death? -
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.
0 Answers
Need More Help?
Get personalized assistance with your technical questions.