init(_:)
Produces an AsyncStream
from an AsyncSequence
by consuming the sequence till it terminates, ignoring any failure.
- iOS
- deprecated
- macOS
- deprecated
- tvOS
- deprecated
- watchOS
- deprecated
init<S>(_ sequence: S) where Element == S.Element, S : Sendable, S : AsyncSequence
Parameters
- sequence
An async sequence.
Useful as a kind of type eraser for live AsyncSequence
-based dependencies.
For example, your feature may want to subscribe to screenshot notifications. You can model this as a dependency client that returns an AsyncStream
:
struct ScreenshotsClient {
var screenshots: () -> AsyncStream<Void>
func callAsFunction() -> AsyncStream<Void> { self.screenshots() }
}
The “live” implementation of the dependency can supply a stream by erasing the appropriate NotificationCenter.Notifications
async sequence:
extension ScreenshotsClient {
static let live = Self(
screenshots: {
AsyncStream(
NotificationCenter.default
.notifications(named: UIApplication.userDidTakeScreenshotNotification)
.map { _ in }
)
}
)
}
While your tests can use AsyncStream.makeStream
to spin up a controllable stream for tests:
func testScreenshots() {
let screenshots = AsyncStream.makeStream(of: Void.self)
let model = withDependencies {
$0.screenshots = { screenshots.stream }
} operation: {
FeatureModel()
}
XCTAssertEqual(model.screenshotCount, 0)
screenshots.continuation.yield() // Simulate a screenshot being taken.
XCTAssertEqual(model.screenshotCount, 1)
}