https://kotlinlang.org logo
Title
t

Teimatini Marin

02/10/2023, 4:39 PM
Hi all! I'm reading a huge file/object from a remote source in bunches... send fragments of the file thru a Flow and wanna process complete lines one by one. I got below implementation... but I was wondering if there is a way to get rid of the var and get a more functional solution. Thanks in advance.
fun main() = runBlocking {
    var lastline = ""
    readHugeFile().collect { value ->
        val lines = (lastline+value).lines()
        lines.dropLast(1).forEach {
            println(it)
        }
        lastline = lines.last()
    }
    println(lastline)
}

fun readHugeFile(): Flow<String> = flowOf(
    """line 1
        |line 2
        |li""".trimMargin(),
    """ne 3
        |line 4
        |lin""".trimMargin(),
    """e 5
        |line 6
        """.trimMargin()
)
a

Alex Prince

02/10/2023, 7:02 PM
.fold
instead of
.collect
is probably what you're looking for
t

Teimatini Marin

02/10/2023, 10:59 PM
Thanks @Alex Prince lesson learned!