https://kotlinlang.org logo
#android
Title
# android
l

lenqnr

07/05/2019, 12:13 PM
I have a
DialogFragment
that calls a `ViewModel`'s method, and the method calls a suspending method via
viewModelScope.launch
. The problem is, when I click OK button on the dialog, I get
kotlinx.coroutines.JobCancellationException: Job was cancelled
error message and the suspending method doesn't work. How can I overcome this problem? I moved the method to my
MainViewModel
and accessed it with
sharedViewModel
, but still the same
JobCancellationException
occured.
r

rkeazor

07/05/2019, 12:21 PM
Does the DialogFragment have its own ViewModel? The lifecycle of the coroutine should be tied to the lifecycle of the dialogfragment
and make sure your only canceling the job, in ViewModel.onCleared
l

lenqnr

07/05/2019, 12:33 PM
I get the same exception whether the DialogFragment has its own ViewModel or using MainViewModel as a shared one. And the coroutine is really simple and there's no canceling code explicitly.
Copy code
fun doSomething() = viewModelScope.launch {
    <http://httpClient.post|httpClient.post><Unit>("<http://example.com>")
}
r

rkeazor

07/05/2019, 12:45 PM
is viewModelScope from Android KTX?
or is that your implementation?
also you should move this conversation to #coroutines
l

lenqnr

07/05/2019, 12:50 PM
OK, thanks.
It's from Android KTX
It was my bad. SharedViewModel works fine.
4 Views