Convert InputStream to Flow

Viewed 1336

I would like to read a file contents and emit a flow for every line of its contents. So, I have to implement a function with the following signature:

fun InputStream.linesToFlow(): Flow<String>

Is there any way to implement this function?

2 Answers

I found the following solution as well:

fun InputStream.linesToFlow() = bufferedReader().lineSequence().asFlow().flowOn(Dispatchers.IO)

You can do this

fun InputStream.linesToFlow(): Flow<String> = channelFlow<String> {
    reader().forEachLine { line -> 
        offer(line)
    }
}
Related