The sad truth is that Scala Futures don't have this basic feature built in. I would therefore strongly suggest using a modern effect system like ZIO or cats-effect, both of which solve this problem and a myriad of others that Futures have. The easiest way to do what you want is to use the bracket
method:
https://zio.dev/docs/overview/overview_handling_resources
Now bracket
works great, but there's a way that usually works even better: the Managed
type. It's virtually impossible to write code that leaks resources if you consistently use Managed
when acquiring resources:
https://zio.dev/docs/datatypes/datatypes_managed
That said,if you absolutely must use Futures, you'll have to write your own try-finally equivalent. Or you can use mine:
def tryFinally[A](tryy: => Future[A])(finallyy: => Future[Any])(
implicit ec: ExecutionContext): Future[A] =
Future.fromTry(Try(tryy)).flatten.transformWith { t =>
finallyy.flatMap((_: Any) => Future.fromTry(t))
}
onComplete
,andThen
ortransform
– Choplogic