Search code examples
scalaakkaslickakka-stream

How to make cleanup when creating a source stream from iterator with Akka stream?


I want to create an Akka Source stream from a JDBC ResultSet, maybe with fromIterator.
(I know Alpakka provide such a source with SlikSession, but it doesn't give me the choice to create the Alpakka source stream from an old style DataSource connection pool, while I want to share the same connection pool for both Akka stream and some old plain SQL queries).
I found an answer to the question Stream records from DataBase using Akka Stream
The only remaining question to me is: how to make cleanup for the data source? like close ResultSet?
It's said it's a good practice to always close the resources.


Solution

  • Source.unfoldResource is your friend, see docs here https://doc.akka.io/docs/akka/current/stream/operators/Source/unfoldResource.html#source-unfoldresource

    It accepts three functions, one to open the resource, one to extract the next element to emit and one to close the resource when done or the stream fails etc.