Coroutines viewModelScope not working with viewModel injection
See original GitHub issueDescribe the bug I have a basic fragment its task is to list to orders.
class MyOrdersFragment : Fragment() {
private val orderRepository: OrderRepository by inject()
private val viewModel: MyOrdersViewModel by viewModel { parametersOf(orderRepository) }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewModel.getOrders()
viewModel.orders.observe(this, Observer<List<Order>> {
//...
})
}
}
And I have viewmodel
class MyOrdersViewModel(private val orderRepository: OrderRepository) : ViewModel() {
val orders = MutableLiveData<List<Order>>()
fun getOrders() {
viewModelScope.launch(Dispatchers.Main) {
orderRepository.getCarts()?.let { mOrders ->
orders.value = mOrders
}
}
}
}
When I open MyOrdersFragment (first time) everything’s working but when I’m close the fragment(MyOrdersFragment) then open it again not create viewmodel’s instance then getOrders function is not working because “viewModelScope” canceled onCleared function of viewmodel
To Reproduce Steps to reproduce the behavior:
- Open a MyOrdersFragment
- Run getOrders function of MyOrdersViewModel
- Close MyOrdersFragment
- MyOrdersViewModel’s viewModelScope is canceled in onCleared function
- Open again MyOrdersFragment
- Run getOrders function but “viewModelScope” is not active then “orderRepository.getCarts()” not worked
Expected behavior When I create a new fragment(like a MyOrdersFragment) it should also create a new viewmodel.
Koin project used and used version (please complete the following information): koin-android:2.0.1 koin-androidx-viewmodel:2.0.1
Additional moduleDefinition kotlinx-coroutines-core:1.1.1 kotlinx-coroutines-android:1.1.1 lifecycle-extensions:2.2.0-alpha01 lifecycle-viewmodel-ktx:2.2.0-alpha01
Issue Analytics
- State:
- Created 4 years ago
- Comments:9 (1 by maintainers)
i found solution for now such.
i’m not use “by viewModel”.
private val viewModel: MyOrdersViewModel by viewModel { parametersOf(orderRepository) }i use “getViewModel” instead of “by viewModel”
Hi, I’m having a similar problem with the viewmodel injection with koin and lifecycle-viewmodel. My activity code is as follows:
this is my viewmodel
The first time I run, everything works correctly, but when I return to the previous screen and return to this activity (RegistryScannerActivity) when calling method
isQRValid()
the corroutine does not runAnyone know why this may be happening, I am noticing that koin generates the instances of the viewModel as singles, is this correct?
the versions of the libraries are the following: