https://kotlinlang.org logo
#stdlib
Title
# stdlib
m

Marc Knaup

08/09/2020, 1:49 PM
It’s confusing that
Flow.toList()
closes the Flow but
Stream.toList()
doesn’t close the Stream. Is that inconsistency intentional?
d

Dominaezzz

08/09/2020, 6:21 PM
What do you mean by "closes"? Flows can't be closed.
m

Marc Knaup

08/09/2020, 6:30 PM
I’m not sure how exactly it works or is called, but Flows can free resources upon cancelation or completion, don’t they? I don’t have to take care of that, e.g. I don’t have to “close” a Flow for reading a file in order to close the file descriptor. With Stream I’ll have to do that, even after a terminal operation like
.toList()
.
d

Dominaezzz

08/09/2020, 6:37 PM
Ah I think I see what you mean. Once a Flow is collected (e.g. calling
toList()
) it must be completely collected (or cancelled). With this rule, a
Flow
can hold on to resources once collection starts and release them upon completion/cancellation. Streams on the other hand, don't have to be completed after iteration begins, so the close method is used to signal a cancellation (I guess). Disclaimer: Haven't properly used Streams.
m

Marc Knaup

08/09/2020, 6:38 PM
Yes, Stream must be closed even after a terminal operation has completed. Hence the confusion when using Kotlin’s
toList()
on each.
d

Dominaezzz

08/09/2020, 6:45 PM
OH! You are referring to Kotlin's
toList()
, I thought it was a special java function. Can you point me to the
toList()
function? I don't think it's the same function for both objects.
m

Marc Knaup

08/09/2020, 6:46 PM
It’s not the same function. It’s just very similar. In both cases you have a stream of value and in one case Kotlin’s
toList()
will close resources, in the other case it won’t. I think it’s a problem with Streams, but because they’re so similar and both coming from Kotlin, it’s still confusing.
13 Views