What is property delegation in Kotlin?
How can you write your own custom delegates?
Examples of how we used delegation at sporttotal.tv and how it made Android databinding much simpler for us
@PreusslerBerlin A Property Delegate package kotlin.reflect public interface KProperty : KCallable { @SinceKotlin("1.1") public val isLateinit: Boolean @SinceKotlin("1.1") public val isConst: Boolean public val getter: Getter …
@PreusslerBerlin Your Property delegates •There is a third function that can be implemented: operator fun provideDelegate( thisRef: Any?, property: KProperty ): ReadOnlyProperty { … } One of the possible use cases of provideDelegate is to check property consistency when the property is created, not only in its getter or setter.
@PreusslerBerlin Our delegates class PlayerLiveFragment : Fragment() { val factory: LiveGameViewModel.Provider by inject() val viewModel: LiveGameViewModel by unsafeLazy { factory(currentClip) }
@PreusslerBerlin We love databinding val label = ObservableField("") @Bindable var label: CharSequence = "" set(value) { field = value notifyPropertyChanged(BR.label) } val label = ”some text"
@PreusslerBerlin We love databinding @Bindable var title: CharSequence = "" set(value) { field = value notifyPropertyChanged(BR. title) } @Bindable var showLoader: Boolean = false set(value) { field = value notifyPropertyChanged(BR. showLoader) } @Bindable var error: String? = null set(value) { field = value notifyPropertyChanged(BR. error) }
@PreusslerBerlin We love databinding @get:Bindable var title: CharSequence by bindable(BR.title, "") @get:Bindable var showLoader: Boolean by bindable(BR.showLoader, false) @get:Bindable var error: String? by bindable(BR.error, null)
@PreusslerBerlin We love databinding @get:Bindable var title: CharSequence by bindable("") @get:Bindable var showLoader: Boolean by bindable(false) @get:Bindable var error: String? by bindable(null)
@PreusslerBerlin Our delegates @get:Bindable var logoVisibility by bindable(View.VISIBLE) @get:Bindable("logoVisibility") val upVisibility: Int get() = logoVisibility.invertVisibility()
@PreusslerBerlin @get:Bindable var currentMainScreen by bindable(Screen.Home.Main()) .eager() .doOnNext { when (it) { is Home -> mainNavigator.goToStart() is Games -> mainNavigator.goToSports() is Profile -> mainNavigator.goToProfile() } }