how to get viewModel by viewModels? (fragment-ktx)

Anmol picture Anmol · Jun 25, 2019 · Viewed 27.1k times · Source

I am working with Single viewModel for the Activity and all of it's fragment.

So to initialise viewmodel if have to write this setup code in onActivityCreated of all the fragment's

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(activity!!).get(NoteViewModel::class.java)
    }

I was going thorough the Android KTX extension page:(refer here)

and i found i can initialise view model like this:

    // Get a reference to the ViewModel scoped to this Fragment
    val viewModel by viewModels<MyViewModel>()

    // Get a reference to the ViewModel scoped to its Activity
    val viewModel by activityViewModels<MyViewModel>()

So I added below dependency's to my gradle(app):

    //ktx android
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.fragment:fragment-ktx:1.0.0'
    implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"

But when i try to use viewModels/activityViewModels in my application their reference in not found.

I want help in how to use these extension's with some basic example i tried searching for examples haven't found any.

Answer

Anmol picture Anmol · Nov 17, 2019

Atlast we we have got stable version.

After moving to implementation 'androidx.fragment:fragment-ktx:1.1.0' i faced another issue.

Compiler Error:

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

build.gradle (Module:app)

compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }

reference

After applying all the above the issue's is resolved.

Thanks everyone.