Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'by viewModels()' Kotlin property delegate unresolved reference

I'm trying to implement viewmodel with kotlin. First I added the needed dependecies:

implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.core:core-ktx:1.2.0' // ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0" // Annotation processor kapt "androidx.lifecycle:lifecycle-compiler:2.2.0" 

Then I created a simple viewmodel:

class MyViewModel: ViewModel() {     val greeting = "Hello World" } 

But when I tried to access the view model from the activity with kotlin property delegate:

val model by viewModels<MyViewModel>() 

The compiler does not resolve viewModels. I don't know what the problem is. Did I miss something?

like image 885
Toni Joe Avatar asked Mar 24 '20 11:03

Toni Joe


People also ask

How to use delegated properties in Kotlin?

To cover these (and other) cases, Kotlin supports delegated properties: class Example { var p: String by Delegate() } The syntax is: val/var <property name>: <Type> by <expression>. The expression after by is a delegate, because get () (and set ()) corresponding to the property will be delegated to its getValue () and setValue () methods.

How to get users from a re-created activity in Kotlin?

// Re-created activities receive the same MyViewModel instance created by the first activity. // Use the 'by viewModels ()' Kotlin property delegate val model: MyViewModel by viewModels () model.getUsers ().observe (this, Observer<List<User>> { users -> // update UI }) } }

What are lazy and observable properties in Kotlin?

Lazy properties: the value is computed only on first access. Observable properties: listeners are notified about changes to this property. Storing properties in a map instead of a separate field for each property. To cover these (and other) cases, Kotlin supports delegated properties:

How to implement annotation processing in Kotlin?

Secondly, the standard android annotation processing ("annotationProcessor") doesn't really work with Kotlin. Instead, use Kotlin's kapt. apply plugin: 'kotlin-kapt'. And in your dependencies section, replace occurences of annotationProcessor (like the above one) with kapt, e.g.


1 Answers

Add these dependencies:

implementation "androidx.activity:activity-ktx:$activity_version" implementation "androidx.fragment:fragment-ktx:$fragment_version" 

You can find the latest versions of libraries here:

https://developer.android.com/jetpack/androidx/releases/activity

https://developer.android.com/jetpack/androidx/releases/fragment

like image 156
IR42 Avatar answered Sep 20 '22 02:09

IR42