SHARE
TWEET

Untitled

a guest Oct 12th, 2017 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fun Any.getDelegate<T>(prop: KProperty<T>): Any {
  2.     return javaClass.getDeclaredField("${prop.name}$delegate").let {
  3.         it.setAccessible(true)
  4.         it.get(this)
  5.     }
  6. }
  7.    
  8. val delegate = a.getDelegate(A::b)
  9.    
  10. val delegate = a.b.delegate
  11.    
  12. fun Any.addObservable<T>(prop: KProperty<T>, observer: (T) -> Unit) {
  13.     getObservableProperty(prop).observers.add(observer)
  14. }
  15.  
  16. fun Any.getObservableProperty<T>(prop: KProperty<T>): ObservableProperty<T> {
  17.     return getDelegate(prop) as ObservableProperty<T>
  18. }
  19.  
  20. fun Any.getDelegate<T>(prop: KProperty<T>): Any {
  21.     return javaClass.getDeclaredField("${prop.name}$delegate").let {
  22.         it.setAccessible(true)
  23.         it.get(this)
  24.     }
  25. }
  26.  
  27. class ObservableProperty<T>(
  28.         initialValue: T,
  29.         initialObservers: Array<(T) -> Unit> = emptyArray()) : ReadWriteProperty<Any?, T> {
  30.  
  31.     private var value = initialValue
  32.  
  33.     public val observers: MutableSet<(T) -> Unit> = initialObservers.toHashSet()
  34.  
  35.     public override fun get(thisRef: Any?, desc: PropertyMetadata): T {
  36.         return value
  37.     }
  38.  
  39.     public override fun set(thisRef: Any?, desc: PropertyMetadata, value: T) {
  40.         this.value = value
  41.         observers.forEach { it(value) }
  42.     }
  43. }
  44.  
  45. class A() {
  46.     var b by ObservableProperty(0)
  47. }
  48.  
  49. fun main(args: Array<String>) {
  50.     val a = A()
  51.  
  52.     a.addObservable(A::b) {
  53.         println("b is now $it")
  54.     }
  55.  
  56.     a.b = 1
  57.     a.b = 2
  58.     a.b = 3
  59. }
  60.    
  61. class A() {
  62.     var foo by ObservableProperty(0)
  63. }
  64.  
  65. class B() {
  66.     var foo by ObservableProperty(0)
  67. }
  68.  
  69. fun main(args: Array<String>) {
  70.     val a = A()
  71.  
  72.     a.addObservable(B::foo) {
  73.         println("b is now $it")
  74.     }
  75.  
  76.     a.foo = 1
  77.     a.foo = 2
  78.     a.foo = 3
  79. }
  80.    
  81. class Stuff(val thing: String)
  82.  
  83. val stuff = Stuff("cool stuff")
  84. val thingFieldName = "${stuff.thing}$delegate"
  85. // value of thingFieldName is now "thing"
RAW Paste Data
Top