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?
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.
// 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 }) } }
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:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With