is there a practical difference between these two ...
# coroutines
j
is there a practical difference between these two ways of converting a
java.util.Stream
to a
Flow
? would the first generally be the preferred way (or is there another, more idiomatic way?):
Copy code
result.iterator().asFlow().onCompletion { result.close() }
vs
Copy code
flow {
    result.use {
        for (edge in it) {
            emit(edge)
        }
    }
}
g
I would create a feature request for kotlinx.coroutines to add Stream.asFlow() Second looks better for me
e
👍 Please do. PR would be also welcome (should be added
kotlinx-coroutines-jdk8
module).
The only design problem that I see is that a
Stream
is single-use, while Flow is multi-use. In the similar case of converting a channel to a flow we’ve picked a different name for conversion method (
consumeAsFlow
) to highlight the fact that the resulting
Flow
is special — it can be consumed just one. In fact, it must be consumed exactly once.
Same with streams. Some streams might be backed by open resources (see
Files
streams) and must be used in order to get the underlying resources closed.