Delegates.observable()

3 0 0
                                        

Delegates.observable() - this is a delegate function from a Delegates class. The difference of this with lazy is that this function has a setValue(). So, you can use the var in here.

How it works?

Observable properties has a listener that everytime you change the value of the property, the listener will know. So, this listener will notify the handler who will handle the changes in the property.

Delegates.observable() has two parameters. The initial value and the lambda function where you can set the property's new value. Since it is a lambda, you can remove this function in the parenthesis and put it in the body of the function. The compiler knows that this function is the other parameter of the function. This lambda function contains three parameters: property, old value and new value.

syntax:

var propertyName: Type by Delegates.observable(initial value){

   (property, old, new) -> //statement

}

===================

fun main(){

    val obj = PracticeObservable()

    obj.message = "ANOTHER WORLD"

}

class PracticeObservable{

    var message: String by Delegates.observable("EARTH"){

        prop, old, new -> println("${prop.name}: Changing $old to $new!")

    }

}

===================

Result:

message: Changing EARTH to ANOTHER WORLD!

Note: If you won't change the value of the property, there will be no display but it runs okay though. That means the listener did not see any changes to the property. So, it did not notify the handler and the handler did not do anything at all.

Kotlin ProgrammingWhere stories live. Discover now