CodexBloom - Programming Q&A Platform

Kotlin Coroutines Unexpectedly Cancelling Job in ViewModel During Configuration Change

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-15
kotlin android coroutines viewmodel Kotlin

I'm dealing with I'm refactoring my project and I'm working with a peculiar scenario with Kotlin Coroutines in my ViewModel where the job seems to be cancelling during configuration changes, specifically when the device is rotated... I have a `viewModelScope` coroutine that fetches data from a remote API, but after the rotation, the data is not being retained and I'm getting a `JobCancellationException`. Here's a simplified version of my code: ```kotlin class MyViewModel : ViewModel() { private val _data = MutableLiveData<Data>() val data: LiveData<Data> get() = _data fun fetchData() { viewModelScope.launch { try { val result = fetchFromApi() // suspending function _data.postValue(result) } catch (e: Exception) { Log.e("MyViewModel", "behavior fetching data", e) } } } } ``` In my Fragment, I'm observing the LiveData like this: ```kotlin class MyFragment : Fragment() { private lateinit var viewModel: MyViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = ViewModelProvider(this).get(MyViewModel::class.java) viewModel.data.observe(viewLifecycleOwner, Observer { data -> // Update UI with data }) viewModel.fetchData() return inflater.inflate(R.layout.fragment_my, container, false) } } ``` I ensured that `fetchData()` is called in `onCreateView` to fetch data right after the Fragment is created, and I also tried moving the call to `onActivityCreated`, but the scenario continues. Using `viewLifecycleOwner` for the observer seems correct, yet the job is still getting cancelled when I rotate the device. I've considered retaining the data with a saved state handle but haven't implemented it yet. Is there a better way to handle this scenario, or am I missing something in the coroutine setup that leads to premature cancellation? I'm working with Kotlin in a Docker container on Linux. Has anyone else encountered this? I recently upgraded to Kotlin 3.11. Any ideas what could be causing this?