arrow-fx / arrow.fx / IO / bracketCase

bracketCase

fun <B> bracketCase(release: (A, ExitCase<Throwable>) -> IOOf<Unit>, use: (A) -> IOOf<B>): IO<B>

A way to safely acquire a resource and release in the face of errors and cancellation. It uses ExitCase to distinguish between different exit cases when releasing the acquired resource.

Bracket exists out of a three stages:

  1. acquisition
  2. consumption
  3. releasing

  4. Resource acquisition is NON CANCELABLE. If resource acquisition fails, meaning no resource was actually successfully acquired then we short-circuit the effect. Reason being, we cannot release what we did not acquire first. Same reason we cannot call use. If it is successful we pass the result to stage 2 use.

  5. Resource consumption is like any other IO effect. The key difference here is that it’s wired in such a way that release will always be called either on ExitCase.Canceled, ExitCase.Error or ExitCase.Completed. If it failed than the resulting IO from bracketCase will be IO.raiseError(e), otherwise the result of use.

  6. Resource releasing is NON CANCELABLE, otherwise it could result in leaks. In the case it throws the resulting IO will be either the error or a composed error if one occurred in the use stage.

Parameters

use - is the action to consume the resource and produce an IO with the result. Once the resulting IO terminates, either successfully, error or disposed, the release function will run to clean up the resources.

release - the allocated resource after the resulting IO of use is terminates.

Do you like Arrow?

Arrow Org
<