@@ -94,30 +94,30 @@ public final class AsyncCurrentValueSubject<Element>: AsyncSubject where Element
9494
9595 func handleNewConsumer( ) -> ( iterator: AsyncBufferedChannel < Element > . Iterator , unregister: @Sendable ( ) -> Void ) {
9696 let asyncBufferedChannel = AsyncBufferedChannel < Element > ( )
97-
98- let terminalState = self . state. withCriticalRegion { state -> Termination ? in
99- state. terminalState
100- }
101-
102- if let terminalState = terminalState, terminalState. isFinished {
103- asyncBufferedChannel. finish ( )
104- return ( asyncBufferedChannel. makeAsyncIterator ( ) , { } )
105- }
106-
107- let consumerId = self . state. withCriticalRegion { state -> Int in
108- state. ids += 1
109- state. channels [ state. ids] = asyncBufferedChannel
110- asyncBufferedChannel. send ( state. current)
111- return state. ids
97+ var consumerId : Int !
98+ var unregister : ( @Sendable ( ) -> Void ) ?
99+
100+ self . state. withCriticalRegion { state in
101+ let terminalState = state. terminalState
102+ if let terminalState, terminalState. isFinished {
103+ asyncBufferedChannel. finish ( )
104+ } else {
105+ state. ids &+= 1
106+ consumerId = state. ids
107+ state. channels [ consumerId] = asyncBufferedChannel
108+ asyncBufferedChannel. send ( state. current)
109+ }
112110 }
113111
114- let unregister = { @Sendable [ state] in
115- state. withCriticalRegion { state in
116- state. channels [ consumerId] = nil
112+ if let consumerId {
113+ unregister = { @Sendable [ state, consumerId] in
114+ state. withCriticalRegion { state in
115+ state. channels [ consumerId] = nil
116+ }
117117 }
118118 }
119119
120- return ( asyncBufferedChannel. makeAsyncIterator ( ) , unregister)
120+ return ( asyncBufferedChannel. makeAsyncIterator ( ) , unregister ?? { } )
121121 }
122122
123123 public func makeAsyncIterator( ) -> AsyncIterator {
0 commit comments