/*:#localized(key: "SequenceOverTime")
 # A sequence whose values arrive over time

 You already know the ordinary `for` loop:

 ```
 for reading in [21, 22, 20] {
     print(reading)
 }
 ```

 That loop has every element in hand before it starts. An **async sequence** is a
 sequence whose elements may not exist yet when the loop begins: each one might need
 a network round-trip, a timer tick, or a sensor sample before it's ready. You loop
 over it with a new spelling, `for await`:

 ```
 for await reading in someAsyncSequence {
     print(reading)
 }
 ```

 Read that as: *"give me the next value; if it isn't ready, suspend this task until
 it is, then run the body."* Everything you learned about `await` in the chapter [Async Await Basics](Async%20Await%20Basics.playgroundchapter/Overview)
 applies: the loop can suspend, other work runs meanwhile, and the page keeps
 breathing. The only new idea is that the suspension happens **once per element**,
 not once for the whole call.

 Here's your first concrete taste. Don't worry yet about how the sequence is built;
 focus on the loop. This stand-in sensor hands you three readings.
 */
//#-editable-code
import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

// A stand-in sensor. Focus on the loop; we build streams like
// this in the next section.
let quickReadings = AsyncStream<Int> { continuation in
    continuation.yield(21)
    continuation.yield(22)
    continuation.yield(20)
    continuation.finish()
}

Task {
    for await reading in quickReadings {
        print("Reading: \(reading)°C")
    }
    print("Done: the sequence ended")
    PlaygroundPage.current.finishExecution()
}
//#-end-editable-code
/*:#localized(key: "SequenceOverTime-2")
 **Watch it run:** you'll see the three readings printed in order, then `Done`. The
 loop ran to the end *by itself*: you never wrote "stop." An async sequence signals
 its own end, and when it does, the `for await` loop finishes and control moves to
 the line after it.

 * callout(Try it): Comment out `continuation.finish()` and run again. The three
 readings still print, but `Done` never does. The loop is still waiting for a next
 value.

 > **Why Task?** A Playground page runs top-to-bottom and can't `await` at the
 > top level, so every `for await` in this chapter lives inside a `Task { }`. The page
 > keeps running while the task iterates. This is the same pattern from the chapter [Tasks and Cancellation](Tasks%20and%20Cancellation.playgroundchapter/Overview).

 [Previous](@previous)  |  page 2 of 7  |  [Next: Producing a Sequence with AsyncStream](@next)
 */
