0Pricing
Swift Academy · Lesson

Producer/consumer, pipelines, timeouts

Build a simple producer/consumer , compose pipelines with AsyncSequence, and implement a timeout by racing a sleep task.

What you will build

This lesson shows three patterns:

  • Producer/consumer with AsyncStream
  • Pipelines using AsyncSequence transforms
  • Timeouts by racing tasks cooperatively

Basic producer/consumer

AsyncStream bridges push-style producers with pull-based for await consumption.

// Producer pushes values; consumer iterates them asynchronously.
func makeNumbers(count: Int) -> AsyncStream<Int> {
    AsyncStream { continuation in
        Task {
            for i in 1...count {
                continuation.yield(i)
                try? await Task.sleep(nanoseconds: 40_000_000) // ~40ms
            }
            continuation.finish()
        }
    }
}

Task {
    let stream = makeNumbers(count: 5)
    for await n in stream {
        print("consume:", n)
    }
    print("done") // after finish()
}

All lessons in this course

  1. Producer/consumer, pipelines, timeouts
  2. Bridging legacy callbacks/Combine to async/await
  3. Testing async code (XCTest)
← Back to Swift Academy