杨锴
2025-04-16 09a372bc45fde16fd42257ab6f78b8deeecf720b
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
//
//  SharedSequence+Concurrency.swift
//  RxCocoa
//
//  Created by Shai Mishali on 22/09/2021.
//  Copyright © 2021 Krunoslav Zaher. All rights reserved.
//
 
#if swift(>=5.6) && canImport(_Concurrency) && !os(Linux)
import Foundation
 
// MARK: - Shared Sequence
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public extension SharedSequence {
    /// Allows iterating over the values of this Shared Sequence
    /// asynchronously via Swift's concurrency features (`async/await`)
    ///
    /// A sample usage would look like so:
    ///
    /// ```swift
    /// for await value in driver.values {
    ///     // Handle emitted values
    /// }
    /// ```
    @MainActor var values: AsyncStream<Element> {
        AsyncStream { continuation in
            // It is safe to ignore the `onError` closure here since
            // Shared Sequences (`Driver` and `Signal`) cannot fail
            let disposable = self.asObservable()
                .subscribe(
                    onNext: { value in continuation.yield(value) },
                    onCompleted: { continuation.finish() }
                )
            continuation.onTermination = { @Sendable termination in
                if termination == .cancelled {
                    disposable.dispose()
                }
            }
        }
    }
}
#endif