"Using ViewModel and LiveData Without Explicit Dependency Declaration in build.gradle"

530 Views Asked by At

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

There are 3 best solutions below

0
Ivan Karlo Rukavina On BEST ANSWER

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
0
Vlad Guriev On

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

2
Shreyas Sparrow On

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