bracket
inline suspend fun <A, B> bracket(crossinline acquire: suspend () -> A, use: suspend (A) -> B, crossinline release: suspend (A) -> Unit): B(source)
Describes a task with safe resource acquisition and release in the face of errors and interruption. It would be the equivalent of an async capable try/catch/finally
statements in mainstream imperative languages for resource acquisition and release.
Parameters
acquire
is the action to acquire the resource.
use
is the action to consume the resource and produce a result. Once the resulting suspend program terminates, either successfully, error or disposed, the release function will run to clean up the resources.
release
is the action that's supposed to release the allocated resource after use
is done, irregardless of its exit condition.
import arrow.fx.coroutines.*
class File(url: String) {
fun open(): File = this
fun close(): Unit {}
override fun toString(): String = "This file contains some interesting content!"
}
suspend fun openFile(uri: String): File = File(uri).open()
suspend fun closeFile(file: File): Unit = file.close()
suspend fun fileToString(file: File): String = file.toString()
suspend fun main(): Unit {
//sampleStart
val res = bracket(
acquire = { openFile("data.json") },
use = { file -> fileToString(file) },
release = { file: File -> closeFile(file) }
)
//sampleEnd
println(res)
}
Content copied to clipboard