Friends, I had a great time trying to implement `s...
# codereview
p
Friends, I had a great time trying to implement
sleepsort
in Kotlin. 😁 The best I could come up with is as follows (playground link):
Copy code
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll

suspend fun main() {
    println(sleepsort(listOf(63, 32, 62, 14, 5)))
}

suspend fun sleepsort(list: List<Int>): List<Int> = coroutineScope {
    buildList {
        list.map { number ->
            async {
                delay(number.toLong())
                add(number)
            }
        }.awaitAll()
    }
}
Do you have any suggestions and/or improvements to make it better (or even worse)? Thank you so much, and season's greetings to everyone! 🎄
j
You don't need `async`'s result, so you can use
launch
instead. Then you also don't need
awaitAll()
(or rather
joinAll()
once you replaced
async
with
launch
), because
coroutineScope
will wait for it's children. You will have to move it inside
buildList
though.
gratitude thank you 1
p
Thanks Joffrey, it works like a charm! gratitude thank you
j
Also, your list is not thread safe. It works in this case because there is only one thread, but if such a function were called in a context with a multi-threaded dispatcher, it might not work properly. You might need to guard it with a mutex or limit parallelism
✔️ 1
r
Since you asked for worse versions, here's one that entirely uses flows blob stuck out tongue :
Copy code
suspend fun sleepsort(list: List<Int>): List<Int> =
        list.asFlow().map { number ->
            flow {
                delay(number.toLong())
                emit(number)
            }
        }.flattenMerge(list.size).toList()
😁 1
gratitude thank you 1