I want to make some cleanup (like close db connection) after a Future
is complete.
Currently I achieve it this way:
Future { ... } onComplete {
case Success(v) =>
// ...
conn.close()
case Failure(ex) =>
// ...
conn.close()
}
There's duplicate code and it's also tedious.
Is there any best practice to this?
Since the same action conn.close()
is performed on both success and failure, consider executing it as a side-effect using andThen
like so
Future { ... } andThen { _ => conn.close() }
Similarly, using onComplete
we could do
Future { ... } onComplete { _ => conn.close() }
The difference between andThen
and onComplete
is that latter will return Unit
, that is, discard the returned value of the Future
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With