Skip to main content
The Search example demonstrates how to build a live search feature with debouncing, API requests, and automatic cancellation. It’s a perfect introduction to effects and async operations in TCA.

Overview

This example shows how to:
  • Debounce user input with SwiftUI’s task modifier
  • Make API requests with URLSession
  • Cancel in-flight requests automatically
  • Handle loading and error states
  • Define custom dependency clients
  • Test async behavior

Implementation

Key Concepts

Debouncing with SwiftUI

Use .task(id:) for automatic debouncing:
When searchQuery changes:
  1. Previous task is automatically cancelled
  2. New task waits 300ms
  3. If not cancelled, sends the debounced action

Automatic Cancellation

Mark effects as cancellable:
When the search query changes, previous requests are automatically cancelled.

Cancel in Flight

Cancel and replace in-flight requests:
Only the most recent forecast request will complete.

Clearing State

Clear results when query is cleared:

Loading States

Track in-flight requests:
Show loading indicator in view:

Custom Dependencies

Define the client interface:
Provide live and test implementations:

Testing

Source Code

View the complete example in the TCA repository:

Next Steps