|
| 1 | +// |
| 2 | +// AsyncValueSubject.swift |
| 3 | +// Supabase |
| 4 | +// |
| 5 | +// Created by Guilherme Souza on 31/10/24. |
| 6 | +// |
| 7 | + |
| 8 | +import ConcurrencyExtras |
| 9 | +import Foundation |
| 10 | + |
| 11 | +/// A thread-safe subject that wraps a single value and provides async access to its updates. |
| 12 | +/// Similar to Combine's CurrentValueSubject, but designed for async/await usage. |
| 13 | +package final class AsyncValueSubject<Value: Sendable>: Sendable { |
| 14 | + |
| 15 | + /// Defines how values are buffered in the underlying AsyncStream. |
| 16 | + package typealias BufferingPolicy = AsyncStream<Value>.Continuation.BufferingPolicy |
| 17 | + |
| 18 | + /// Internal state container for the subject. |
| 19 | + struct MutableState { |
| 20 | + var value: Value |
| 21 | + var continuations: [UInt: AsyncStream<Value>.Continuation] = [:] |
| 22 | + var count: UInt = 0 |
| 23 | + } |
| 24 | + |
| 25 | + let bufferingPolicy: BufferingPolicy |
| 26 | + let mutableState: LockIsolated<MutableState> |
| 27 | + |
| 28 | + /// Creates a new AsyncValueSubject with an initial value. |
| 29 | + /// - Parameters: |
| 30 | + /// - initialValue: The initial value to store |
| 31 | + /// - bufferingPolicy: Determines how values are buffered in the AsyncStream (defaults to .unbounded) |
| 32 | + package init(_ initialValue: Value, bufferingPolicy: BufferingPolicy = .unbounded) { |
| 33 | + self.mutableState = LockIsolated(MutableState(value: initialValue)) |
| 34 | + self.bufferingPolicy = bufferingPolicy |
| 35 | + } |
| 36 | + |
| 37 | + deinit { |
| 38 | + finish() |
| 39 | + } |
| 40 | + |
| 41 | + /// The current value stored in the subject. |
| 42 | + package var value: Value { |
| 43 | + mutableState.value |
| 44 | + } |
| 45 | + |
| 46 | + /// Sends a new value to the subject and notifies all observers. |
| 47 | + /// - Parameter value: The new value to send |
| 48 | + package func yield(_ value: Value) { |
| 49 | + mutableState.withValue { |
| 50 | + $0.value = value |
| 51 | + |
| 52 | + for (_, continuation) in $0.continuations { |
| 53 | + continuation.yield(value) |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + /// Resume the task awaiting the next iteration point by having it return |
| 59 | + /// nil, which signifies the end of the iteration. |
| 60 | + /// |
| 61 | + /// Calling this function more than once has no effect. After calling |
| 62 | + /// finish, the stream enters a terminal state and doesn't produce any |
| 63 | + /// additional elements. |
| 64 | + package func finish() { |
| 65 | + for (_, continuation) in mutableState.continuations { |
| 66 | + continuation.finish() |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + /// An AsyncStream that emits the current value and all subsequent updates. |
| 71 | + package var values: AsyncStream<Value> { |
| 72 | + AsyncStream(bufferingPolicy: bufferingPolicy) { continuation in |
| 73 | + insert(continuation) |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + /// Observes changes to the subject's value by executing the provided handler. |
| 78 | + /// - Parameters: |
| 79 | + /// - priority: The priority of the task that will observe changes (optional) |
| 80 | + /// - handler: A closure that will be called with each new value |
| 81 | + /// - Returns: A task that can be cancelled to stop observing changes |
| 82 | + @discardableResult |
| 83 | + package func onChange( |
| 84 | + priority: TaskPriority? = nil, |
| 85 | + _ handler: @escaping @Sendable (Value) -> Void |
| 86 | + ) -> Task<Void, Never> { |
| 87 | + let stream = self.values |
| 88 | + return Task(priority: priority) { |
| 89 | + for await value in stream { |
| 90 | + if Task.isCancelled { |
| 91 | + break |
| 92 | + } |
| 93 | + handler(value) |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + /// Adds a new continuation to the subject and yields the current value. |
| 99 | + private func insert(_ continuation: AsyncStream<Value>.Continuation) { |
| 100 | + mutableState.withValue { state in |
| 101 | + continuation.yield(state.value) |
| 102 | + let id = state.count + 1 |
| 103 | + state.count = id |
| 104 | + state.continuations[id] = continuation |
| 105 | + |
| 106 | + continuation.onTermination = { [weak self] _ in |
| 107 | + self?.remove(continuation: id) |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /// Removes a continuation when it's terminated. |
| 113 | + private func remove(continuation id: UInt) { |
| 114 | + mutableState.withValue { |
| 115 | + _ = $0.continuations.removeValue(forKey: id) |
| 116 | + } |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +extension AsyncValueSubject where Value == Void { |
| 121 | + package func yield() { |
| 122 | + self.yield(()) |
| 123 | + } |
| 124 | +} |
0 commit comments