Hyperlinkv0.8.0-beta.28

Layer

Layer.launchconsteffect/Layer.ts:2167
<RIn, E, ROut>(self: Layer<ROut, E, RIn>): Effect<never, E, RIn>

Builds this layer and keeps it alive until the returned effect is interrupted.

When to use

Use when you model your entire application as a layer, such as an HTTP server.

Details

When the returned effect is interrupted, the layer scope is closed and all finalizers registered during layer acquisition are run.

Example (Launching an application layer)

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

class HttpServer extends Context.Service<HttpServer, {
  readonly start: () => Effect.Effect<string>
  readonly stop: () => Effect.Effect<string>
}>()("HttpServer") {}

class Logger extends Context.Service<Logger, {
  readonly log: (msg: string) => Effect.Effect<void>
}>()("Logger") {}

// Server layer that starts an HTTP server
const serverLayer = Layer.effect(HttpServer, Effect.gen(function*() {
  yield* Console.log("Starting HTTP server...")

  return {
    start: Effect.fn("HttpServer.start")(function*() {
        yield* Console.log("Server listening on port 3000")
        return "Server started"
      }),
    stop: Effect.fn("HttpServer.stop")(function*() {
        yield* Console.log("Server stopped gracefully")
        return "Server stopped"
      })
  }
}))

const loggerLayer = Layer.succeed(Logger, {
  log: Effect.fn("Logger.log")((msg: string) => Console.log(`[LOG] ${msg}`))
})

// Application layer combining all services
const appLayer = Layer.mergeAll(serverLayer, loggerLayer)

// Launch the application - runs until interrupted
const application = appLayer.pipe(
  Layer.launch,
  Effect.tapError((error) => Console.log(`Application failed: ${error}`)),
  Effect.tap(() => Console.log("Application completed"))
)

// This will run forever until externally interrupted
// Effect.runFork(application)
converting
Source effect/Layer.ts:21672 lines
export const launch = <RIn, E, ROut>(self: Layer<ROut, E, RIn>): Effect<never, E, RIn> =>
  internalEffect.scoped(internalEffect.andThen(build(self), internalEffect.never))