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
edwardwongtl
11/05/2018, 4:12 AM
Is this similar to what
distinctBy {}
does?
m
mersan
11/05/2018, 10:10 AM
I believe
distinctBy
is for `Channel`s
t
Timmy
11/05/2018, 4:37 PM
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.