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

Joe

10/07/2019, 3:46 PM
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

gildor

10/07/2019, 3:53 PM
I would create a feature request for kotlinx.coroutines to add Stream.asFlow() Second looks better for me
e

elizarov

10/08/2019, 2:24 PM
👍 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.
2 Views