Hyperlinkv0.8.0-beta.28

Layer

Layer.buildWithScopeconsteffect/Layer.ts:732
(scope: Scope.Scope): <RIn, E, ROut>(
  self: Layer<ROut, E, RIn>
) => Effect<Context.Context<ROut>, E, RIn>
<RIn, E, ROut>(self: Layer<ROut, E, RIn>, scope: Scope.Scope): Effect<
  Context.Context<ROut>,
  E,
  RIn
>

Builds a layer using an explicit scope.

When to use

Use to control the lifetime of layer resources with a scope supplied by the caller.

Details

Resources created by the layer are released when the supplied scope is closed, unless a resource extends its own scope.

Example (Building a layer with an explicit scope)

import { Context, Effect, Layer, Scope } from "effect"

class Database extends Context.Service<Database, {
  readonly query: (sql: string) => Effect.Effect<string>
}>()("Database") {}

// Build a layer with explicit scope control
const program = Effect.gen(function*() {
  const scope = yield* Effect.scope

  const dbLayer = Layer.effect(Database, Effect.gen(function*() {
    console.log("Initializing database...")
    yield* Scope.addFinalizer(
      scope,
      Effect.sync(() => console.log("Database closed"))
    )
    return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) }
  }))

  // Build with specific scope - resources tied to this scope
  const context = yield* Layer.buildWithScope(dbLayer, scope)
  const database = Context.get(context, Database)

  return yield* database.query("SELECT * FROM users")
  // Database will be closed when scope is closed
})
destructors
Source effect/Layer.ts:73214 lines
export const buildWithScope: {
  (scope: Scope.Scope): <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Effect<Context.Context<ROut>, E, RIn>
  <RIn, E, ROut>(self: Layer<ROut, E, RIn>, scope: Scope.Scope): Effect<Context.Context<ROut>, E, RIn>
} = dual(2, <RIn, E, ROut>(
  self: Layer<ROut, E, RIn>,
  scope: Scope.Scope
): Effect<Context.Context<ROut>, E, RIn> =>
  core.withFiber((fiber) =>
    buildWithMemoMap(
      self,
      CurrentMemoMap.forkOrCreate(fiber.context),
      scope
    )
  ))
Referenced by 1 symbols