Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 12 additions & 23 deletions Sources/ComposableArchitecture/Store.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ public final class Store<State, Action> {
private var isSending = false
private var parentCancellable: AnyCancellable?
private let reducer: (inout State, Action) -> Effect<Action, Never>
private var synchronousActionsToSend: [Action] = []
private var bufferedActions: [Action] = []

/// Initializes a store from an initial state, a reducer, and an environment.
Expand Down Expand Up @@ -360,41 +359,31 @@ public final class Store<State, Action> {
}

func send(_ action: Action) {
if !self.isSending {
self.synchronousActionsToSend.append(action)
} else {
self.bufferedActions.append(action)
return
}

while !self.synchronousActionsToSend.isEmpty || !self.bufferedActions.isEmpty {
let action =
!self.synchronousActionsToSend.isEmpty
? self.synchronousActionsToSend.removeFirst()
: self.bufferedActions.removeFirst()
self.bufferedActions.append(action)
guard !self.isSending else { return }

self.isSending = true
let effect = self.reducer(&self.state.value, action)
self.isSending = true
var currentState = self.state.value
defer {
self.state.value = currentState
self.isSending = false
}

while !self.bufferedActions.isEmpty {
let action = self.bufferedActions.removeFirst()
let effect = self.reducer(&currentState, action)

var didComplete = false
let uuid = UUID()

var isProcessingEffects = true
let effectCancellable = effect.sink(
receiveCompletion: { [weak self] _ in
didComplete = true
self?.effectCancellables[uuid] = nil
},
receiveValue: { [weak self] action in
if isProcessingEffects {
self?.synchronousActionsToSend.append(action)
} else {
self?.send(action)
}
self?.send(action)
}
)
isProcessingEffects = false

if !didComplete {
self.effectCancellables[uuid] = effectCancellable
Expand Down
2 changes: 1 addition & 1 deletion Tests/ComposableArchitectureTests/StoreTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,6 @@ final class StoreTests: XCTestCase {

viewStore.send(0)

XCTAssertEqual(emissions, [0, 1, 2, 3])
XCTAssertEqual(emissions, [0, 3])
}
}