flat Map
Create a resource value of B from a resource A by mapping f.
Useful when there is a need to create resources that depend on other resources, for combining independent values zip provides nicer syntax without the need for callback nesting.
import arrow.fx.coroutines.*
object Connection
class DataSource {
fun connect(): Unit = println("Connecting dataSource")
fun connection(): Connection = Connection
fun close(): Unit = println("Closed dataSource")
}
class Database(private val database: DataSource) {
fun init(): Unit = println("Database initialising . . .")
fun shutdown(): Unit = println("Database shutting down . . .")
}
suspend fun main(): Unit {
//sampleStart
val dataSource = resource {
DataSource().also { it.connect() }
} release DataSource::close
fun database(ds: DataSource): Resource<Database> =
resource {
Database(ds).also(Database::init)
} release Database::shutdown
dataSource.flatMap(::database)
.use { println("Using database which uses dataSource") }
//sampleEnd
}
Content copied to clipboard
See also
for combining independent resources in parallel