https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

Casey Brooks

10/15/2019, 7:26 PM
Is there anything out there for repeatedly reading input from stdin, something like a suspending version of
readLine()
in a while loop?
t

trevjones

10/15/2019, 8:36 PM
seems like you could create a flow that reads from stdin and yields once per line?
z

Zach Klippenstein (he/him) [MOD]

10/15/2019, 8:58 PM
Copy code
val File.lines: Flow<String>
    get() = flow<String> {
      useLines { lines ->
        emitAll(lines.asFlow())
      }
    }.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
o

octylFractal

10/15/2019, 9:32 PM
that might close the source too early, perhaps
reader.lineSequence().asFlow().onCompletion { reader.close() }.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
z

Zach Klippenstein (he/him) [MOD]

10/15/2019, 9:43 PM
Why would it close the source too early?
useLines
won’t close the source until the block exits, which won’t happen until the collector finishes processing the last line. If anything it will close the source too late, which I think is what your solution fixes.
t

trevjones

10/15/2019, 9:45 PM
asFlow().onCompletion
seems suspect to leak on anything but the happy path?
o

octylFractal

10/15/2019, 9:50 PM
I'm not sure what you mean by that Trevor?
onCompletion
is called upon exception as well iirc
t

trevjones

10/15/2019, 9:50 PM
copy that, rx brain leaking through. not yet a flow user myself
o

octylFractal

10/15/2019, 9:51 PM
zach, yes, I apologize for that. Your version works as well.
z

Zach Klippenstein (he/him) [MOD]

10/16/2019, 6:19 PM
@octylFractal Yours is objectively better, with mine if the last
emit
call suspends for a long time the file handle is effectively leaked. Could happen if a
buffer(RENDEZVOUS)
was chained right after the
flowOn
.
2 Views