0

UPDATE: As ianhanniballake pointed out in his comment, I needed to use viewModelScope instead of lifecycleScope. This is now resolved.


I am trying to use androidx.lifecycle.lifecycleScope in my Android Native Jetpack Compose app. I have the following in my build.gradle file:

    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.5.1'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1'

I have added the following import to my MainViewModel:

import androidx.lifecycle.lifecycleScope

I am not getting any errors on the import, and if I hover over it, it seems to be telling me the correct information that I am expecting about where it is coming from:

public val LifecycleOwner.lifecycleScope: LifecycleCoroutineScope
CoroutineScope tied to this LifecycleOwner's Lifecycle.
This scope will be cancelled when the Lifecycle is destroyed.
This scope is bound to Dispatchers.Main.immediate.
  androidx.lifecycle   LifecycleOwnerKt.class 
  Gradle: androidx.lifecycle:lifecycle-runtime-ktx:2.5.1@aar (classes.jar)

However, when I try to reference lifecycleScope in my code:

    fun isSplashScreenOptChecked() {
        lifecycleScope.launch() {
            userPrefRepo.shouldDisplaySplashScreen().collect {
                withContext(Dispatchers.Main) {
                    showSplashScreen.value = it
                }
            }
        }
    }

I am getting the following error:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val LifecycleOwner.lifecycleScope: LifecycleCoroutineScope defined in androidx.lifecycle

I am not sure what to do next, because I copied this code from several different examples I found online, and I seem to be doing exactly what they are.

  • are you koin for dependency injection by any chance – Ivan Feb 03 '23 at 20:20
  • I'm using Hilt - is that a potentail source of my problem? – Dave Westerman Feb 03 '23 at 20:43
  • 2
    A `ViewModel` is not a `LifecycleOwner`, so this API isn't what you should be using at all. Did you mean to use [`viewModelScope`](https://developer.android.com/topic/libraries/architecture/coroutines#viewmodelscope)? – ianhanniballake Feb 03 '23 at 21:20
  • I'm pretty much a newbie, so I wasn't aware that's what I needed. The examples were putting all the code in the MainActivity, which isn't what I wanted. I will give the viewModelScope a try! – Dave Westerman Feb 03 '23 at 21:39

0 Answers0