Kotlin for Android Developers
Download 1.04 Mb. Pdf ko'rish
|
Kotlin for Android Developers Learn Kotlin the Easy Way While Developing an Android App ( PDFDrive )
Observable
This delegate will help us detect changes on any property we need to observe. It will execute the lambda expression we specify, every time the set function is called. So after the new value is assigned, we receive the delegated property, the old value and the new one. 16 Application Singleton and Delegated Properties 59 1 class ViewModel(val db: MyDatabase) { 2 3 var myProperty by Delegates.observable("") { 4 d, old, new -> 5 db.saveChanges(this, new) 6 } 7 8 } This example represents some kind of ViewModel class which is aware of myProperty changes, and saves them to the database every time a new value is assigned Vetoable This is a special kind of observable that lets you decide whether the value must be saved or not. It can be used to check some conditions before saving a value. 1 var positiveNumber = Delegates.vetoable(0) { 2 d, old, new -> 3 new >= 0 4 } The previous delegate will only allow the new value to be saved if it’s a positive number. Inside lambdas, the latest line represents the return value. You don’t need to use the return word (it won’t compile indeed). lateinit Sometimes we need something else to initialise a property, but we don’t have the required state available in the constructor, or we even are not able to access to them. This second case happens now and then in Android: in activities, fragments, services, broadcast receivers… However, a non abstract property needs a value before the constructor finishes executing. We cannot just wait until we want, in order to assign a value to the property. We have at least a couple of options. The first one is to use a nullable type and set it to null, until we have the real value. But we then need to check everywhere throughout the code whether the property is null or not. If we are sure this property is not going to be null at any moment before using it, this may make us write some unnecessary code. The second option is to use lateinit , which identifies that the property should have a non-nullable value, but its assignment will be delayed. If the value is requested before it is assigned, it will throw an exception that clearly identifies the property being accessed. 16 Application Singleton and Delegated Properties 60 lateinit is not exactly a delegate, but a property modifier, and that’s why it must be written before the property. This could be helpful in the App singleton example: 1 class App : Application() { 2 3 companion object { 4 lateinit var instance: App 5 } 6 7 override fun onCreate() { 8 super.onCreate() 9 instance = this 10 } 11 } Download 1.04 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling