Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 425
user6502167 Avatar asked Mar 03 '23 00:03

user6502167


1 Answers

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.

like image 167
Mario Galic Avatar answered May 09 '23 05:05

Mario Galic