Android data binding with Kotlin, BaseObservable, and a custom delegate
You can annotate the default getter or setter without providing a body.
var bar: String by Delegates.observable("") { prop, old, new ->
notifyPropertyChanged(BR.bar)
}
@Bindable get
There is a shortcut annotation use-site target which does the same thing.
@get:Bindable var bar: String by Delegates.observable("") { prop, old, new ->
notifyPropertyChanged(BR.bar)
}
Additionaly to the accepted answer - sometimes you need variables passed in constructor. It is easy to do too.
class Foo(_bar: String) : BaseObservable() {
@get:Bindable var bar by Delegates.observable(_bar) { _, _, _ ->
notifyPropertyChanged(BR.bar)
}
}
Sometimes we have to save object using parcel, I had some problems using delegete, so code looks like this:
@Parcelize
class Foo(private var _bar: String) : BaseObservable(), Parcelable {
@IgnoredOnParcel
@get:Bindable var bar
get() = _bar
set(value) {
_bar = value
notifyPropertyChanged(BR.bar)
}
}