flat Map
Deprecated
flatMap is redundant and will be removed in Arrow 2.x.x in favor of the DSL. In case you think this method should stay, please provide feedback and your use-case on https://github.com/arrow-kt/arrow/issues
Replace with
import arrow.fx.coroutines.resource
Content copied to clipboard
resource { f(this.bind()).bind() }Content copied to clipboard
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 {
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") }
}Content copied to clipboard
See also
to combine independent resources together
for combining independent resources in parallel