-
Notifications
You must be signed in to change notification settings - Fork 26
/
AsyncZipSequence.swift
56 lines (48 loc) · 1.65 KB
/
AsyncZipSequence.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// AsyncZipSequence.swift
//
//
// Created by Thibault Wittemberg on 24/09/2022.
//
/// `zip` produces an `AsyncSequence` that combines the latest elements from sequences according to their temporality
/// and emits an array to the client. If any Async Sequence ends successfully or fails with an error, so to does the zipped
/// Async Sequence.
///
/// ```
/// let asyncSequence1 = [1, 2, 3, 4, 5].async
/// let asyncSequence2 = [1, 2, 3, 4, 5].async
/// let asyncSequence3 = [1, 2, 3, 4, 5].async
/// let asyncSequence4 = [1, 2, 3, 4, 5].async
/// let asyncSequence5 = [1, 2, 3, 4, 5].async
///
/// let zippedAsyncSequence = zip(asyncSequence1, asyncSequence2, asyncSequence3, asyncSequence4, asyncSequence5)
///
/// for await element in zippedAsyncSequence {
/// print(element) // will print -> [1, 1, 1, 1, 1] [2, 2, 2, 2, 2] [3, 3, 3, 3, 3] [4, 4, 4, 4, 4] [5, 5, 5, 5, 5]
/// }
/// ```
/// Use the `zip(_:)` function to create an `AsyncZipSequence`.
public func zip<Base: AsyncSequence>(_ bases: Base...) -> AsyncZipSequence<Base> {
AsyncZipSequence(bases)
}
public struct AsyncZipSequence<Base: AsyncSequence>: AsyncSequence
where Base: Sendable, Base.Element: Sendable {
public typealias Element = [Base.Element]
public typealias AsyncIterator = Iterator
let bases: [Base]
init(_ bases: [Base]) {
self.bases = bases
}
public func makeAsyncIterator() -> AsyncIterator {
Iterator(bases)
}
public struct Iterator: AsyncIteratorProtocol {
let runtime: ZipRuntime<Base>
init(_ bases: [Base]) {
self.runtime = ZipRuntime(bases)
}
public func next() async rethrows -> Element? {
try await self.runtime.next()
}
}
}