Running suspend function in `finally` block … foo...
# coroutines
e
Running suspend function in
finally
block … foot marksmanship or not? 🤔 (Or put another way, is it a bad idea to run a suspend function in the finally block? Use case is I don’t want to catch errors from
suspendFunA()
but I need to cleanup resources used & reset a lock within
suspendFunB()
)
Copy code
try {
~    suspendFunA()
   } finally {
~    suspendFunB()
   }
s
The foot-gun is when the coroutine was cancelled. In that case,
suspendFunB()
will just fail again as soon as it tries to suspend. To fix it:
Copy code
try {
  suspendFunA()
} finally {
  withContext(NonCancellable) {
    suspendFunB()
  } 
}
👍 2
Other than that, it's absolutely fine.
e
Nice thanks!
y
Arrow has a
Resource
datatype that does exactly this (with
NonCancellable
) so I would say yes this is the way to go. You might wanna use their
ResourceScope
abstraction if you're doing this a lot