Skip to content

Commit e2fcfbb

Browse files
author
Brennan Stehling
committed
adds forEach function to AsyncSequence
1 parent c27cc12 commit e2fcfbb

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import Foundation
2+
3+
public extension AsyncSequence {
4+
func forEach(_ block: (Element) async throws -> Void) async rethrows {
5+
for try await element in self {
6+
try await block(element)
7+
}
8+
}
9+
}

Tests/AsyncChannelKitTests/AsyncChannelKitTests.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ final class AsyncChannelKitTests: XCTestCase {
1212
enum Failure: Error {
1313
case unluckyNumber
1414
}
15+
16+
actor Output<Element> {
17+
var elements: [Element] = []
18+
func append(_ element: Element) {
19+
elements.append(element)
20+
}
21+
}
22+
1523
let sleepSeconds = 0.1
1624

1725
func testNumberSequence() async throws {
@@ -35,6 +43,28 @@ final class AsyncChannelKitTests: XCTestCase {
3543
XCTAssertEqual(input, output)
3644
}
3745

46+
func testNumberSequenceUsingForEach() async throws {
47+
let input = [1, 2, 3, 4, 5]
48+
let channel = AsyncChannel<Int>()
49+
50+
// load all numbers into the channel with delays
51+
Task {
52+
try await send(elements: input, channel: channel, sleepSeconds: sleepSeconds)
53+
}
54+
55+
let output = Output<Int>()
56+
57+
print("-- before --")
58+
await channel.forEach { element in
59+
print(element)
60+
await output.append(element)
61+
}
62+
print("-- after --")
63+
64+
let outputElements = await output.elements
65+
XCTAssertEqual(input, outputElements)
66+
}
67+
3868
func testStringSequence() async throws {
3969
let input = ["one", "two", "three", "four", "five"]
4070
let channel = AsyncChannel<String>()

0 commit comments

Comments
 (0)