Skip to content

Instantly share code, notes, and snippets.

@yaraki
Created August 8, 2019 07:07
Show Gist options
  • Save yaraki/11d6d265418954ef86fa0616858a4f0a to your computer and use it in GitHub Desktop.
Save yaraki/11d6d265418954ef86fa0616858a4f0a to your computer and use it in GitHub Desktop.
Sleep sort
package com.example.android.flow
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import org.junit.Test
class FlowTest {
fun sleepSort(input: List<Int>): Flow<Int> {
return channelFlow {
input.map { i ->
async {
delay(i * 100L)
send(i)
}
}.awaitAll()
}
}
@Test
fun sorted() = runBlocking {
val input = listOf(9, 0, 8, 1, 7, 2, 6, 3, 5, 4)
assertThat(sleepSort(input).toList()).isOrdered()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment