Effects
Effects represent side effects in TCA. They allow reducers to interact with the outside world, such as making API calls, reading from disk, or starting timers, while keeping the reducer logic pure and testable.The Effect Type
TheEffect type is a wrapper around asynchronous operations that can emit actions:
Effect.swift
Creating Effects
Effect.none
When no side effect is needed:Effect.run
The primary way to create effects with async/await:Effect.run automatically captures dependencies and provides a send function for emitting actions back into the system.Effect.send
Immediately emit a single action:The Send Type
TheSend type allows effects to emit actions back into the system:
Effect.swift
Using Send
Send implements callAsFunction, so you call it like a function: send(.action) instead of send.send(.action).Effect Patterns
Async Sequences
Stream values from async sequences:Long-Running Effects
Error Handling
Use thecatch parameter to handle errors:
Task Priority
Specify priority for effects:Combining Effects
Merge
Run multiple effects concurrently:Concatenate
Run effects sequentially:Cancellation
Effects are automatically cancelled when:- The store is deallocated
- The view disappears (if using
.task { await store.send(.task).finish() }) - You explicitly cancel them
Manual Cancellation
Use cancellation IDs to manually cancel effects:Cancel All Effects
Testing Effects
Exhaustive Testing
TestStore requires you to assert on all effects:
Non-Exhaustive Testing
For flexibility in tests:Debouncing and Throttling
Debounce
Delay effect execution until input stops:Throttle
Limit effect execution frequency:Effect Animations
Send actions with animations:EffectOf Type Alias
UseEffectOf for less verbose type signatures:
Effect.swift
Best Practices
1
Keep Effects Focused
Each effect should do one thing. Use
.merge() to combine multiple focused effects:2
Always Handle Errors
Use the
catch parameter or do-catch blocks:3
Use Cancellation IDs
Always provide cancellation IDs for long-running effects:
4
Test All Effects
Use
TestStore to verify effects emit the expected actions:5
Check for Cancellation
Respect cancellation in long-running effects:
Common Pitfalls
Related Topics
- Reducers - Where effects are returned
- Testing - Testing effects with TestStore
- Dependencies - Injecting dependencies into effects
- Store - How effects are executed