Effect module is the foundation of the Effect library, providing a powerful way to model and compose asynchronous, concurrent, and effectful computations.
Overview
AnEffect<A, E, R> represents a computation that:
- May succeed with a value of type
A - May fail with an error of type
E - Requires a context/environment of type
R
Key Features
- Type-safe error handling: Errors are tracked in the type system
- Resource management: Automatic cleanup with scoped resources
- Structured concurrency: Safe parallel and concurrent execution
- Composable: Effects can be combined using operators like
flatMap,map,zip - Testable: Built-in support for testing with controlled environments
- Interruptible: Effects can be safely interrupted and cancelled
Creating Effects
From Plain Values
From Promises
From Callbacks
Composing Effects with Effect.gen
UseEffect.gen to write code in an imperative style similar to async/await:
Using Effect.fn for Reusable Functions
When writing functions that return an Effect, useEffect.fn to use the generator syntax:
Error Handling
Combining Multiple Effects
Running Effects
Type Utilities
Best Practices
- Prefer Effect.gen: Use
Effect.genfor better readability instead of deeply nestedpipechains - Use Effect.fn for functions: When creating functions that return Effects, wrap them with
Effect.fn - Handle errors explicitly: Don’t ignore error types - handle them with
catchTag,catchAll, or similar operators - Keep effects pure: Effects should be descriptions of computations, not perform side effects when created
- Use services for dependencies: Inject dependencies through the Effect context rather than importing them directly