-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathAsyncJustSequence.swift
54 lines (44 loc) · 1.4 KB
/
AsyncJustSequence.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
//
// AsyncJustSequence.swift
//
//
// Created by Thibault Wittemberg on 04/01/2022.
//
/// `AsyncJustSequence` is an AsyncSequence that outputs a single value and finishes.
/// If the parent task is cancelled while iterating then the iteration finishes before emitting the value.
///
/// ```
/// let justSequence = AsyncJustSequence<Int>(1)
/// for await element in justSequence {
/// // will be called once with element = 1
/// }
/// ```
public struct AsyncJustSequence<Element>: AsyncSequence {
public typealias Element = Element
public typealias AsyncIterator = Iterator
let element: Element?
public init(_ element: Element?) {
self.element = element
}
public func makeAsyncIterator() -> AsyncIterator {
Iterator(element: self.element)
}
public struct Iterator: AsyncIteratorProtocol {
let element: Element?
let isConsumed = ManagedCriticalState<Bool>(false)
public mutating func next() async -> Element? {
guard !Task.isCancelled else { return nil }
let shouldEarlyReturn = self.isConsumed.withCriticalRegion { isConsumed -> Bool in
if !isConsumed {
isConsumed = true
return false
}
return true
}
if shouldEarlyReturn { return nil }
return self.element
}
}
}
extension AsyncJustSequence: Sendable where Element: Sendable {}
extension AsyncJustSequence.Iterator: Sendable where Element: Sendable {}