Kotlin recommended way of unregistering a listener with a SAM -


so have interactor performs insert operation realm , notifies insertion completed realchangelistener. this:

fun insertcar(item: car) {         realm.dointransaction {             val car = car(...)             val copy = copytorealm(car)             copy.addchangelistener(...)         }     } 

i can way:

fun insertcar(item: car, listener: realmchangelistener<car>) {             realm.dointransaction {                 val car = car(...)                 val copy = copytorealm(car)                 copy.addchangelistener(listener)             }         } 

and access this:

realminteractor.insertcar(item, realmchangelistener {    // here }) 

but have no way of removing listener

realminteractor.insertcar(item, realmchangelistener {    // here    it.removechangelistener(this) }) 

this point class located not actual listener

i can this:

fun insertcar(item: car, doafterchange (car) -> unit) {                 realm.dointransaction {                     val car = car(...)                     val copy = copytorealm(car)                     copy.addchangelistener(realmchangelistener{                     doafterchange()                     })                 }             } 

but have sam inside sam (too overkill imo)

i can this:

fun insertcar(item: car, listener: realmchangelistener<car>) {                 realm.dointransaction {                     val car = car(...)                     val copy = copytorealm(car)                     copy.addchangelistener(listener)                 }             }  realminteractor.insertcar(item, object : realmchangelistener<car> {                         override fun onchange(element: car?) {                             ...                             element?.removechangelistener(this)                         }                     }) 

which works verbose.

so how deal , considered best approach?

you can create generic method perform run-once listener. along lines of:

fun <t> createinrealm(objectfactory: () -> t, changelistener: (t) -> unit) {     realm.dointransaction {          val obj = objectfactory()          val copy = copytorealm(obj)          copy.addchangelistener(object : realmchangelistener<t> {              override fun onchange(element: t) {                  changelistener()                  element.removechangelistener(this)              }          }     } } 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -