https://kotlinlang.org logo
Title
l

LastExceed

03/28/2022, 10:34 AM
any1 know a more elegant way to prevent the trailing delay?
repeat(10) {
    foo()
    delay(500) //problem: causes trailing delay
}
i could of course do this:
foo()
repeat(10) {
    delay(500)
    foo()
}
but it looks kinda ugly to me
p

phldavies

03/28/2022, 10:37 AM
repeat(10) {
    if (it > 0) delay(500)
    foo()
}
should do the trick
:nice: 5
l

LastExceed

03/28/2022, 10:40 AM
nice!
m

Michael de Kaste

03/28/2022, 12:58 PM
I kinda prefer the original solution because you know when exactly you expect the delay not to show up. Now you are giving your program extra computational time, even though you knew when exactly it would happen. Granted, an if check is nothing 😛
l

LastExceed

03/28/2022, 3:03 PM
that kinda reminds me of someone telling me to use
inline
functions whereever possible for performance gains. even intellij tells you to stop because of how insignificant the difference is
at some point you trade performance for convenience. thats also why we aren't programming in ASM anymore
k

Klitos Kyriacou

03/28/2022, 4:49 PM
A perverted way (for amusement only):
Array(10) { foo() }.joinToString(delay(500).let {""})
l

LastExceed

03/28/2022, 4:55 PM
that wont work. the array will be fully initialized first,
joinToString
is called afterwards
the separater is evaluated once in the beginning
🤦‍♂️ 2
✔️ 2
e

ephemient

03/28/2022, 5:50 PM
if you wanted to go down that road,
flow { repeat(10) { emit(foo()) } }
    .fold(false) { doDelay, _ ->
        if (doDelay) delay(100)
        true
    }
(the slightly-more natural
sequence { repeat(10) { yield(foo()) } }
    .zipWithNext { _, _ -> delay(100) }
    .toList()
doesn't work with suspend functions)
I'm not recommending that, btw ;)
l

LastExceed

03/28/2022, 5:55 PM
this is so cursed, i love it
🤣 1
m

Michael de Kaste

03/29/2022, 8:31 AM
@LastExceed I agree with performance vs convenience, but in this case we are talking about practically the same lines of code. There's no convenience loss here, just a perception of beauty 😉