Is there a better way to do this? I'm trying to cr...
# codereview
m
Is there a better way to do this? I'm trying to create distinct function for functions
Copy code
fun <T, B> distinct(body: (T) -> B): (T) -> B {
  val lastInput = AtomicReference<T>()
  val lastReturn = AtomicReference<B>()
  return {
    if (lastInput.get() != it) {
      lastInput.set(it)
      lastReturn.set(body(it))
    }
    lastReturn.get()
  }
}
e
Is this similar to what
distinctBy {}
does?
m
I believe
distinctBy
is for `Channel`s
t
If the AtomicReference is supposed to be for thread safety it is not being used correctly. The two .set() could be executed by different threads and lead to mismatched lastInput/lastReturn. You could either go with a simple synchronized lock, properly use the AtomicReference (maybe updateAndGet?, propably a single AtomicReference for input/output) or go with a fancy lock free solution based on coroutines, i.e. have one actor handle all requests. The solution you pick depends on how much concurrency you are expecting.
☝️ 1