question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Coroutines viewModelScope not working with viewModel injection

See original GitHub issue

Describe 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:

  1. Open a MyOrdersFragment
  2. Run getOrders function of MyOrdersViewModel
  3. Close MyOrdersFragment
  4. MyOrdersViewModel’s viewModelScope is canceled in onCleared function
  5. Open again MyOrdersFragment
  6. 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:closed
  • Created 4 years ago
  • Comments:9 (1 by maintainers)

github_iconTop GitHub Comments

7reactions
utkukutlucommented, Aug 16, 2019

There is no fix yet for this. Did you manage to observe the livedata in any way yet from there?

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”

private lateinit var viewModel: MyOrdersViewModel 
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
    ): View? {

    viewModel = getViewModel<MyOrdersViewModel>()

} 
2reactions
lterminiellocommented, Mar 9, 2020

Hi, I’m having a similar problem with the viewmodel injection with koin and lifecycle-viewmodel. My activity code is as follows:

class RegistryScannerActivity : ScannerActivity() {

    private val viewModel : RegistryScannerViewModel by viewModel()

     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initObservers()
    }

    override fun onScan(result: BarcodeResult) {
        stopScanner()
        viewModel.isQRValid(result.text)
   }
}. 

this is my viewmodel

class RegistryScannerViewModel(
    private val validateQrRegistryRepository: ValidateQrRegistryRepository
) : ViewModel() {

    private val _qrValidResult: MutableLiveData<Result<Boolean>> = MutableLiveData()
    val qrValidResult: LiveData<Result<Boolean>> get() = _qrValidResult

    fun isQRValid(qrValue: String) {
        coroutineScope.launch {
            _qrValidResult.value = Result.Success(validateQrRegistryRepository.isValidQr(qrValue))
        }
    }

    override fun onCleared() {
        super.onCleared()
        _qrValidResult.value = null
    }
}

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 run

Anyone 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:

implementation 'org.koin:koin-android-viewmodel:2.0.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
Read more comments on GitHub >

github_iconTop Results From Across the Web

Easy Coroutines in Android: viewModelScope - Medium
If your ViewModel is getting destroyed, all the asynchronous work that it might be doing must be stopped. Otherwise, you'll waste resources and...
Read more >
Best practices for coroutines in Android
Inject Dispatchers; Suspend functions should be safe to call from the main thread; The ViewModel should create coroutines ...
Read more >
How to inject viewModelScope for Android unit test with Kotlin ...
Run a unit test on Android's ViewModel view state values saved in a Kotlin Flow value. Observed. Module with the Main dispatcher had...
Read more >
Kotlin Coroutines : View Model Scope example - YouTube
Get My Advanced Android Development Course at Udemy (Only $9.99) using this highly discounted link Become a professional, highly paid, ...
Read more >
Coroutine Support in ViewModels using the new ... - craigrussell
How to use Coroutines in ViewModels, making use of the new ViewModelScope extension property. This allows coroutines to be cancelled automatically when the ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found