Hyperlinkv0.8.0-beta.28

Stream

Stream.serviceOptionconsteffect/Stream.ts:444
<I, S>(service: Context.Key<I, S>): Stream<Option.Option<S>>

Optionally accesses a service from the context and emits the result as a single element.

When to use

Use when you need a stream that emits an optional service from the context without requiring that service to be present.

Example (Accessing an optional service as a stream)

import { Context, Effect, Option, Stream } from "effect"

class Greeter extends Context.Service<Greeter, {
  readonly greet: (name: string) => string
}>()("Greeter") {}

const stream = Stream.serviceOption(Greeter).pipe(
  Stream.map((maybeGreeter) =>
    Option.match(maybeGreeter, {
      onNone: () => "No greeter",
      onSome: (greeter) => greeter.greet("World")
    })
  )
)

const program = Effect.gen(function*() {
  return yield* stream.pipe(
    Stream.provideService(Greeter, {
      greet: (name) => `Hello, ${name}!`
    }),
    Stream.runCollect
  )
})

Effect.runPromise(program)
// Output: [ "Hello, World!" ]
context
Source effect/Stream.ts:4442 lines
export const serviceOption = <I, S>(service: Context.Key<I, S>): Stream<Option.Option<S>> =>
  fromEffect(Effect.serviceOption(service))