I am having this interesting problem. I need to do some work immediately after insertion, but viewModelScope randomly, or at least it looks like randomly, skips functions except for the first one.
Example:
fun insertItem(item: SingleItem) = viewModelScope.launch {
itemsRepository.insertItem(item)
increaseAmount(item.catId)
}
So in this example everything runs ok only after fresh app install, but then on the next app launches second function "increaseAmount" will be randomly skipped and i don`t know why. And it doesn't matter what goes after first function. I tried simple "Log" and it gets skipped as well. Is it normal for viewModelScope?
EDIT Checked for exceptions. Second function throws an exception that the job was cancelled:
kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelling}@2d87ff
Also, in my Fragment it is called like this:
viewModel.insertItem(newItem)
root.findNavController().popBackStack()
So after calling this function i go back to previous Fragment. Is it possible that viewModel gets destroyed before it finishes executing all work?
itemRepository.insertItemmay throw exception. Have you checked it?