common fun <B> flatMap(f: (A) -> Resource<B>): Resource<B>

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 {
    } release Database::shutdown

    .use { println("Using database which uses dataSource") }

See also


arrow.fx.coroutines.Resource for combining independent resources in parallel

Do you like Arrow?

Arrow Org