From 0801c718ca657779ccae8f138ebc5b6452e11ba8 Mon Sep 17 00:00:00 2001 From: "Won Heo (Woody)" Date: Tue, 5 Aug 2025 11:14:27 +0900 Subject: [PATCH] [Feature] Add batchDispatch --- ReSwift/CoreTypes/Store.swift | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/ReSwift/CoreTypes/Store.swift b/ReSwift/CoreTypes/Store.swift index 9774fdd7..bee6ba0d 100644 --- a/ReSwift/CoreTypes/Store.swift +++ b/ReSwift/CoreTypes/Store.swift @@ -19,6 +19,8 @@ open class Store: StoreType { private(set) public var state: State! { didSet { + guard canEmitNewState else { return } + subscriptions.forEach { if $0.subscriber == nil { subscriptions.remove($0) @@ -34,10 +36,10 @@ open class Store: StoreType { private var reducer: Reducer var subscriptions: Set = [] + + private var canEmitNewState: Bool = true - private var isDispatching = Synchronized(false) - - /// Indicates if new subscriptions attempt to apply `skipRepeats` + /// Indicates if new subscriptions attempt to apply `skipRepeats` /// by default. fileprivate let subscriptionsAutomaticallySkipRepeats: Bool @@ -156,25 +158,22 @@ open class Store: StoreType { // swiftlint:disable:next identifier_name open func _defaultDispatch(action: Action) { - guard !isDispatching.value else { - raiseFatalError( - "ReSwift:ConcurrentMutationError- Action has been dispatched while" + - " a previous action is being processed. A reducer" + - " is dispatching an action, or ReSwift is used in a concurrent context" + - " (e.g. from multiple threads). Action: \(action)" - ) - } - - isDispatching.value { $0 = true } let newState = reducer(action, state) - isDispatching.value { $0 = false } - state = newState } open func dispatch(_ action: Action) { dispatchFunction(action) } + + open func batchDispatch(_ actions: [Action]) { + canEmitNewState = false + actions.forEach { self.dispatch($0) } + canEmitNewState = true + + let newState = state + state = newState + } @available(*, deprecated, message: "Deprecated in favor of https://github.com/ReSwift/ReSwift-Thunk") open func dispatch(_ actionCreatorProvider: @escaping ActionCreator) {