|
| 1 | +// |
| 2 | +// Streamed.swift |
| 3 | +// |
| 4 | +// |
| 5 | +// Created by Thibault Wittemberg on 20/03/2022. |
| 6 | +// |
| 7 | + |
| 8 | +/// A type that streams a property marked with an attribute as an AsyncSequence. |
| 9 | +/// |
| 10 | +/// Streaming a property with the `@Streamed` attribute creates an AsyncSequence of this type. You access the AsyncSequence with the `$` operator, as shown here: |
| 11 | +/// |
| 12 | +/// class Weather { |
| 13 | +/// @Streamed var temperature: Double |
| 14 | +/// init(temperature: Double) { |
| 15 | +/// self.temperature = temperature |
| 16 | +/// } |
| 17 | +/// } |
| 18 | +/// |
| 19 | +/// let weather = Weather(temperature: 20) |
| 20 | +/// Task { |
| 21 | +/// for try await element in weather.$temperature { |
| 22 | +/// print ("Temperature now: \(element)") |
| 23 | +/// } |
| 24 | +/// } |
| 25 | +/// |
| 26 | +/// // ... later in the application flow |
| 27 | +/// |
| 28 | +/// weather.temperature = 25 |
| 29 | +/// |
| 30 | +/// // Prints: |
| 31 | +/// // Temperature now: 20.0 |
| 32 | +/// // Temperature now: 25.0 |
| 33 | +@propertyWrapper public struct Streamed<Element> { |
| 34 | + let currentValue: AsyncStreams.CurrentValue<Element> |
| 35 | + |
| 36 | + /// Creates the streamed instance with an initial wrapped value. |
| 37 | + /// |
| 38 | + /// Don't use this initializer directly. Instead, create a property with the `@Streamed` attribute, as shown here: |
| 39 | + /// |
| 40 | + /// @Streamed var lastUpdated: Date = Date() |
| 41 | + /// |
| 42 | + /// - Parameter wrappedValue: The stream's initial value. |
| 43 | + public init(wrappedValue: Element) { |
| 44 | + self.currentValue = AsyncStreams.CurrentValue<Element>(wrappedValue) |
| 45 | + self.wrappedValue = wrappedValue |
| 46 | + } |
| 47 | + |
| 48 | + public var wrappedValue: Element { |
| 49 | + willSet { |
| 50 | + self.currentValue.element = newValue |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /// The property for which this instance exposes an AsyncSequence. |
| 55 | + /// |
| 56 | + /// The ``Streamed/projectedValue`` is the property accessed with the `$` operator. |
| 57 | + public var projectedValue: AnyAsyncSequence<Element> { |
| 58 | + self.currentValue.eraseToAnyAsyncSequence() |
| 59 | + } |
| 60 | +} |
0 commit comments