Last active
May 16, 2019 10:04
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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