-
Notifications
You must be signed in to change notification settings - Fork 26
/
AsyncThrowingJustSequence.swift
56 lines (46 loc) · 1.58 KB
/
AsyncThrowingJustSequence.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
//
// AsyncThrowingJustSequence.swift
//
//
// Created by Thibault Wittemberg on 04/01/2022.
//
/// `AsyncThrowingJustSequence` is an AsyncSequence that outputs a single value from a throwing closure and finishes.
/// If the parent task is cancelled while iterating then the iteration finishes before emitting the value.
///
/// ```
/// let justSequence = AsyncThrowingJustSequence<Int> { 1 }
/// for try await element in justSequence {
/// // will be called once with element = 1
/// }
/// ```
public struct AsyncThrowingJustSequence<Element>: AsyncSequence, Sendable {
public typealias Element = Element
public typealias AsyncIterator = Iterator
let factory: @Sendable () async throws -> Element?
public init(_ element: Element?) where Element: Sendable {
self.factory = { element }
}
public init(factory: @Sendable @escaping () async throws -> Element?) {
self.factory = factory
}
public func makeAsyncIterator() -> AsyncIterator {
Iterator(factory: self.factory)
}
public struct Iterator: AsyncIteratorProtocol, Sendable {
let factory: @Sendable () async throws -> Element?
let isConsumed = ManagedCriticalState<Bool>(false)
public mutating func next() async throws -> 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 }
let element = try await self.factory()
return element
}
}
}