Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Property Delegation with Kotlin for Android

Property Delegation with Kotlin for Android

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

Danny Preussler

June 20, 2019
Tweet

More Decks by Danny Preussler

Other Decks in Programming

Transcript

  1. @PreusslerBerlin Property Delegates public fun <T> lazy( initializer: () ->

    T) : Lazy<T> = SynchronizedLazyImpl( initializer )
  2. @PreusslerBerlin Property Delegates public fun <T> lazy( initializer: () ->

    T) : Lazy<T> = SynchronizedLazyImpl( initializer )
  3. @PreusslerBerlin Property Delegates public fun <T> lazy( initializer: () ->

    T) : Lazy<T> = SynchronizedLazyImpl( initializer )
  4. @PreusslerBerlin Property Delegates inline fun <reified T : Any> ComponentCallbacks.inject(

    name: String = "", scope: Scope? = null, noinline parameters: ParameterDefinition = emptyParameterDefinition() ) = lazy { get<T>(name, scope, parameters) }
  5. @PreusslerBerlin Property Delegates inline fun <reified T : Any> ComponentCallbacks.inject(

    name: String = "", scope: Scope? = null, noinline parameters: ParameterDefinition = emptyParameterDefinition() ) = lazy { get<T>(name, scope, parameters) }
  6. @PreusslerBerlin Property Delegates inline fun <reified T : ViewModel> LifecycleOwner.viewModel(

    key: String? = null, name: String? = null, noinline parameters: ParameterDefinition = emptyParameterDefinition() ) = viewModelByClass(T::class, key, name, null, parameters)
  7. @PreusslerBerlin Property Delegates inline fun <reified T : ViewModel> LifecycleOwner.viewModel(

    key: String? = null, name: String? = null, noinline parameters: ParameterDefinition = emptyParameterDefinition() ) = viewModelByClass(T::class, key, name, null, parameters)
  8. @PreusslerBerlin Property Delegates fun <T : ViewModel> LifecycleOwner.viewModelByClass( clazz: KClass<T>,

    key: String? = null, name: String? = null, from: ViewModelStoreOwnerDefinition? = null, parameters: ParameterDefinition = emptyParameterDefinition() ) = lazy { getViewModelByClass(clazz, key, name, from, parameters) }
  9. @PreusslerBerlin A Property Delegate fun censored(): String = ““ operator

    fun String.getValue( thisRef: Any?, property: KProperty<*> ): Int = this.replace(“sucks”, “is suboptimal”) operator fun String.setValue( thisRef: Any?, property: KProperty<*>, String: value ) { ??? }
  10. @PreusslerBerlin A Property Delegate class CensorProperty(var message: String?) : ReadWriteProperty<Any?,

    String?> { override fun getValue( thisRef: Any?, property: KProperty<*>) = message override fun setValue( thisRef: Any?, property: KProperty<*>, value: String? ) { message = value?.replace( “sucks”, “is suboptimal”) }
  11. @PreusslerBerlin A Property Delegate class CensorProperty(var message: String?) : ReadWriteProperty<Any?,

    String?> { override fun getValue( thisRef: Any?, property: KProperty<*>) = message override fun setValue( thisRef: Any?, property: KProperty<*>, value: String? ) { message = value?.replace( “sucks”, “is suboptimal”) } }
  12. @PreusslerBerlin A Property Delegate class CensorProperty(var message: String?) : ReadWriteProperty<Any?,

    String?> { override fun getValue( thisRef: Any?, property: KProperty<*>) = message override fun setValue( thisRef: Any?, property: KProperty<*>, value: String? ) { message = value?.replace( “sucks”, “is suboptimal”) } }
  13. @PreusslerBerlin A Property Delegate package kotlin.reflect public interface KProperty<out R>

    : KCallable<R> { @SinceKotlin("1.1") public val isLateinit: Boolean @SinceKotlin("1.1") public val isConst: Boolean public val getter: Getter<R> …
  14. @PreusslerBerlin A Property Delegate class CensorProperty(var message: String?) : ReadWriteProperty<Any?,

    String?> { override fun getValue( thisRef: Any?, property: KProperty<*>) = message override fun setValue( thisRef: Any?, property: KProperty<*>, value: String? ) { message = value?.replace( “sucks”, “is suboptimal”) } }
  15. @PreusslerBerlin A Property Delegate class CensorProperty(var message: String?) : ReadWriteProperty<Any?,

    String?> { override fun getValue( thisRef: Any?, property: KProperty<*>) = message override fun setValue( thisRef: Any?, property: KProperty<*>, value: String? ) { message = value?.replace( “sucks”, “is suboptimal”) } }
  16. @PreusslerBerlin A Property Delegate class CensorProperty(var message: String?) : ReadWriteProperty<FrameLayout?,

    String?> { override fun getValue( thisRef: FrameLayout?, property: KProperty<*>) = message override fun setValue( thisRef: FrameLayout?, property: KProperty<*>, value: String? ) { message = value?.replace( “sucks”, “is suboptimal”) } }
  17. @PreusslerBerlin A Property Delegate var message: String by censored() fun

    censored(message: String = ““) = CensorProperty(message)
  18. @PreusslerBerlin Your Property delegates •There is a third function that

    can be implemented: operator fun provideDelegate( thisRef: Any?, property: KProperty<*> ): ReadOnlyProperty<MyUI, T> { … } 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.
  19. @PreusslerBerlin Our delegates class PlayerLiveFragment : Fragment() { val factory:

    LiveGameViewModel.Provider by inject() val viewModel: LiveGameViewModel by unsafeLazy { factory(currentClip) }
  20. @PreusslerBerlin Our delegates fun toggleOnFirstAccess(initial: Boolean) = object : ReadOnlyProperty<Any?,

    Boolean> { private val value = AtomicBoolean(initial) override fun getValue( thisRef: Any?, property: KProperty<*>) = value.getAndSet(initial.not()) }
  21. @PreusslerBerlin Our delegates fun toggleOnFirstAccess(initial: Boolean) = object : ReadOnlyProperty<Any?,

    Boolean> { private val value = AtomicBoolean(initial) override fun getValue( thisRef: Any?, property: KProperty<*>) = value.getAndSet(initial.not()) }
  22. @PreusslerBerlin Our delegates fun toggleOnFirstAccess(initial: Boolean) = object : ReadOnlyProperty<Any?,

    Boolean> { private val value = AtomicBoolean(initial) override fun getValue( thisRef: Any?, property: KProperty<*>) = value.getAndSet(initial.not()) }
  23. @PreusslerBerlin Our delegates class DisposableProperty( private var disposable: Disposable?) :ReadWriteProperty<Any?,

    Disposable?> { override fun setValue( thisRef: Any?, property: KProperty<*>, value: Disposable?) { disposable?.dispose() disposable = value } override fun getValue( thisRef: Any?, property: KProperty<*>) = disposable }
  24. @PreusslerBerlin Our delegates class DisposableProperty( private var disposable: Disposable?) :ReadWriteProperty<Any?,

    Disposable?> { override fun setValue( thisRef: Any?, property: KProperty<*>, value: Disposable?) { disposable?.dispose() disposable = value } override fun getValue( thisRef: Any?, property: KProperty<*>) = disposable }
  25. @PreusslerBerlin Our delegates class DisposableProperty( private var disposable: Disposable?) :ReadWriteProperty<Any?,

    Disposable?> { override fun setValue( thisRef: Any?, property: KProperty<*>, value: Disposable?) { disposable?.dispose() disposable = value } override fun getValue( thisRef: Any?, property: KProperty<*>) = disposable }
  26. @PreusslerBerlin Our delegates var playingAd by observable(false) .distinctUntilChanged() .doOnTrue {

    onAdsStarted() } .doOnFalse { onAdsStopped() } override fun onTimelineChanged( timeline: Timeline?, manifest: Any?, reason: Int) { playingAd = exoPlayer.isPlayingAd }
  27. @PreusslerBerlin Observable? inline fun <T> observable( initialValue: T, crossinline onChange:

    ( property: KProperty<*>, oldValue: T, newValue: T ) -> Unit ): ReadWriteProperty<Any?, T> var max: Int by observable(0) { property, oldValue, newValue -> … }
  28. @PreusslerBerlin Observable? •We didn‘t use the Kotlin observable: •Dont care

    about previous value or kproperty •Would not work with the chaining
  29. @PreusslerBerlin Since Kotlin 1.3 public inline fun <T> vetoable( initialValue:

    T, crossinline onChange: ( property: KProperty<*>, oldValue: T, newValue: T) -> Boolean) : ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) { }
  30. @PreusslerBerlin Since Kotlin 1.3 public inline fun <T> vetoable( initialValue:

    T, crossinline onChange: ( property: KProperty<*>, oldValue: T, newValue: T) -> Boolean) : ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) { }
  31. @PreusslerBerlin Since Kotlin 1.3 public inline fun <T> vetoable( initialValue:

    T, crossinline onChange: ( property: KProperty<*>, oldValue: T, newValue: T) -> Boolean) : ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) { }
  32. @PreusslerBerlin We love databinding val label = ObservableField("") @Bindable var

    label: CharSequence = "" set(value) { field = value notifyPropertyChanged(BR.label) } val label = ”some text"
  33. @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) }
  34. @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)
  35. @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)
  36. @PreusslerBerlin @get:Bindable var currentMainScreen by bindable<Screen>(Screen.Home.Main()) .eager() .doOnNext { when

    (it) { is Home -> mainNavigator.goToStart() is Games -> mainNavigator.goToSports() is Profile -> mainNavigator.goToProfile() } }