Any built-in way to create a `Flow` of lines from ...
# announcements
j
Any built-in way to create a
Flow
of lines from a
File
(on JVM)? I thought about several options, like: -
FileReader(file).buffered().lineSequence().asFlow()
(requires to close reader externally) -
flow { FileReader(file).useLines { lines -> lines.forEach { emit(it) } } }
(broken reader closure it early termination) But I believe that would be using the blocking file API behind the scenes. Is this OK, though? Should I implement my flow on top of
AsynchronousFileChannel
instead?
t
I think this is completely OK, as you can change the Flow Dispatcher with
flowOn
.
👍 2
j
Yes, I intended to use the
flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
with it, but I'm not comfortable enough with the implementation details of flows and coroutines to be sure that this is OK compared to using actual asynchronous APIs in the first place
I finally went for the following:
Copy code
fun File.lineFlow(): Flow<String> {
    val reader = bufferedReader()
    return reader.buffered()
        .lineSequence()
        .asFlow()
        .onCompletion { reader.close() }
        .flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
}