fix
杨锴
2025-06-16 3fa53409f5132333ce6d83fff796e108ddd62090
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
//  Observable+Concurrency.swift
//  RxSwift
//
//  Created by Shai Mishali on 22/09/2021.
//  Copyright © 2021 Krunoslav Zaher. All rights reserved.
//
 
#if swift(>=5.6) && canImport(_Concurrency)
import Foundation
 
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public extension ObservableConvertibleType {
    /// Allows iterating over the values of an Observable
    /// asynchronously via Swift's concurrency features (`async/await`)
    ///
    /// A sample usage would look like so:
    ///
    /// ```swift
    /// do {
    ///     for try await value in observable.values {
    ///         // Handle emitted values
    ///     }
    /// } catch {
    ///     // Handle error
    /// }
    /// ```
    var values: AsyncThrowingStream<Element, Error> {
        AsyncThrowingStream<Element, Error> { continuation in
            var isFinished = false
            let disposable = asObservable().subscribe(
                onNext: { value in continuation.yield(value) },
                onError: { error in
                    isFinished = true
                    continuation.finish(throwing: error)
                },
                onCompleted: {
                    isFinished = true
                    continuation.finish()
                },
                onDisposed: {
                    guard !isFinished else { return }
                    continuation.finish(throwing: CancellationError() )
                }
            )
            continuation.onTermination = { @Sendable termination in
                if case .cancelled = termination {
                    disposable.dispose()
                }
            }
        }
    }
}
 
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public extension AsyncSequence {
    /// Convert an `AsyncSequence` to an `Observable` emitting
    /// values of the asynchronous sequence's type
    ///
    /// - returns: An `Observable` of the async sequence's type
    func asObservable() -> Observable<Element> {
        Observable.create { observer in
            let task = Task {
                do {
                    for try await value in self {
                        observer.onNext(value)
                    }
 
                    observer.onCompleted()
                } catch {
                    observer.onError(error)
                }
            }
 
            return Disposables.create { task.cancel() }
        }
    }
}
#endif