//arrow-fx-coroutines/arrow.fx.coroutines/Resource/flatMap

flatMap

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 {
  //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
}

See also

common

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

Do you like Arrow?

Arrow Org
<