0

I've noticed that in some of my Android projects, I'm able to access ViewModel and LiveData classes without explicitly adding the following dependencies to my build.gradle file:

implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version")

I'm curious as to why this is happening. Shouldn't I need to declare these dependencies to use ViewModel and LiveData in my project? Could there be any factors or configurations that allow me to access these components?

I'd appreciate any insights into how this is possible...

3 Answers 3

2

You could get those 2 as transitive dependencies, if you included some dependecy that depends on ViewModel and LiveData. You are probably getting those when you are using some other dependencies that have ViewModel and LiveData bundled. For example, if you use "androidx.navigation:navigation-fragment-ktx", you would get those 2 bundled.

You can easily check this with command

./gradlew app:dependencies
Sign up to request clarification or add additional context in comments.

Comments

1

It means they have been added transitively. You can run the app:dependencies Gradle task to view the dependency tree.

Comments

1

When you create a new project these dependency will be added by default.

implementation("androidx.core:core-ktx:1.9.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.9.0")

Here core-ktx dependency contains lifecycle dependency.

Appcompat and material dependency contains core dependency

So when you comment these three lines you cant able to access livedata and viewmodel.

Hope this helps

2 Comments

I have already tried removing androidx.core:core-ktx but I am still able to access these.
Did you remove the appcompat dependency and material dependency if not please remove it. Maximum of android dependency add core dependency so that you may able to access the viewmodel. dependencies { /*implementation("androidx.core:core-ktx:1.9.0") implementation("androidx.appcompat:appcompat:1.6.1") */ testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.1.5") androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") } Can you please share your dependency part of build.gradle of your project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.