Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Observables


What if you want to know when the delegated property is changed? You might need to react to the change and call some other code. The Delegates object comes with the following construct to allow you to achieve exactly that:

    fun <T> observable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit):
       ReadWriteProperty<Any?, T>

We will see this at work with the following simple example. Every time the value property is changed, the onValueChanged() method is called and we print out the new value:

   class WithObservableProp {
      var value: Int by Delegates.observable(0) { p, oldNew, newVal -> onValueChanged()
    }
 
    private fun onValueChanged() {
      println("value has changed:$value")
    }
   }
   val onChange = WithObservableProp()
   onChange.value = 10
   onChange.value = -20

There is another observable implementation offered out of...