Skip to content

Instantly share code, notes, and snippets.

@fteychene
Last active May 16, 2019 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fteychene/c22d5b30123df236ffa6b3007eff5575 to your computer and use it in GitHub Desktop.
Save fteychene/c22d5b30123df236ffa6b3007eff5575 to your computer and use it in GitHub Desktop.
InputStream to combine a Stream of other InputStream in a lazy way in Kotlin
class StreamInputStream(private val source: Stream<out InputStream>) : InputStream() {
private val iterator by lazy {
source
.flatMap {
generateSequence {
val result = it.read(); if (result == -1) {
it.close(); null
} else result
}.asStream()
}
.iterator()
}
@Throws(IOException::class)
override fun read(): Int =
if (!iterator.hasNext()) -1
else iterator.next()
@Throws(IOException::class)
override fun close() = source.close()
}
var counter = 0
const val LOGLINE = "Une ligne de log pas super longue mais bon qui commence a faire un petit peu quand même, non par ce que c'est vrai qu'il faut que ce soit long mais je sais pas a quel point\n"
val generator = {
counter++;
if (counter < 1000) LOGLINE.repeat(1000000) else null
}
fun main() {
val source = generateSequence(generator)
.asStream()
.map { it.byteInputStream() as InputStream }
val combined = StreamInputStream(source)
val reader = combined.bufferedReader()
do {
val line = reader.readLine()
println(line)
} while (line != null)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment