2

I have an Iterator[InputStream] which i map over to retrieve the individual results:

val streams: Iterator[InputStream[CustomType]] = retrieveStreams()
val results: Iterator[MyResultType] = streams flatMap (c => transformToResult(c))

This works as expected, meaning I can retrieve values of type MyResultType from the results iterator. The only problem I have is that the individual InputStreams are never being closed. Is there any way to do this?

neptoon
  • 53
  • 1
  • 9

1 Answers1

2

There is no magic way to close it, or at least to guarantee that it will get closed. Thus you have to close each stream yourself. Take a look at the Loan Pattern which makes it less error prone: Loaner Pattern in Scala.

In your case you don't have a single resource to release but rather a collection of resources, so adjust your custom loan pattern accordingly.

Since you are dealing with Iterator you might have unlimited supply of InputStreams, in that case your transformToResult function would have to close the stream or something else at the element level.

It could look something like this:

val streams: Iterator[InputStream[CustomType]] = retrieveStreams()
val results: Iterator[MyResultType] =
  streams flatMap (c => yourLoaner(c)(transformToResult))
Community
  • 1
  • 1
yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65