scalafutureresource-cleanup

Best practice to make cleanup after Scala Future is complete


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?


Solution

  • 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.