Did anyone get issue with viewModelScope ? `viewMo...
# android
b
Did anyone get issue with viewModelScope ?
viewModelScope.launch
work like a charm until I’m navigate to other screen => viewModel go to onClear() => Then I’m navigate back and try to call
viewModelScope.launch
but it didn’t anything. Any idea for this ?
c
The
viewModelScope
gets cancelled once the ViewModel itself is cleared, and you can’t launch new jobs in a cancelled coroutineScope. You might have an issue with how you’re accessing your ViewModel. How are you creating your ViewModel?
🙌 1
b
@Casey Brooks I’m using this syntax to create a ViewModel
Copy code
protected open val viewModel: VM by lazy { ViewModelProvider(this)[ViewModelClass::kt] }
So I pass
this
as the viewModelStoreOwner. Any incorrect at here
c
Yeah, I’m thinking
by lazy
isn’t what you want, that it will hold onto a ViewModel instance longer than it should. You should probably be using the
by viewModels()
function from the
fragment-ktx
library
b
@Casey Brooks Thanks. Let me try
@Casey Brooks by viewModels() didn’t resolve my issue. Any other idea
t
are you accessing a viewmodel from a fragment? and then navigating to other fragments? as you will need to obtian your view model within the fragment using
Copy code
val viewModel: MyViewModel by activityViewModels<YourViewModel>()
and NOT
Copy code
val viewModel by viewModels<YourViewModel>()