Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thread safety #1

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
19 changes: 5 additions & 14 deletions ReSwift/CoreTypes/Store.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,15 @@ open class Store<State: StateType>: StoreType {
}
}

///The dispatch function to be used.
///
///Note: The default dispatch function runs alls reductions within a thread-safe synchronized block.
public var dispatchFunction: DispatchFunction!

private var reducer: Reducer<State>

var subscriptions: [SubscriptionType] = []

private var isDispatching = false

public required init(
reducer: @escaping Reducer<State>,
state: State?,
Expand Down Expand Up @@ -109,20 +110,10 @@ open class Store<State: StateType>: StoreType {

// swiftlint:disable:next identifier_name
open func _defaultDispatch(action: Action) {
guard !isDispatching else {
raiseFatalError(
"ReSwift:ConcurrentMutationError- Action has been dispatched while" +
" a previous action is action is being processed. A reducer" +
" is dispatching an action, or ReSwift is used in a concurrent context" +
" (e.g. from multiple threads)."
)
}

isDispatching = true
objc_sync_enter(self)
let newState = reducer(action, state)
isDispatching = false

state = newState
objc_sync_exit(self)
}

open func dispatch(_ action: Action) {
Expand Down
44 changes: 37 additions & 7 deletions ReSwiftTests/StoreDispatchTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,33 @@ class StoreDispatchTests: XCTestCase {
}

/**
it throws an exception when a reducer dispatches an action
it accepts actions coming from multiple threads and handles them synchronously
*/
func testThrowsExceptionWhenReducersDispatch() {
// Expectation lives in the `DispatchingReducer` class
let reducer = DispatchingReducer()
store = Store(reducer: reducer.handleAction, state: TestAppState())
reducer.store = store
store.dispatch(SetValueAction(10))
func testDispatchInMultipleThreadsAreSynchronized() {
store.dispatch(SetValueAction(5))

let firstAction = DelayedAction(3)
let secondAction = DelayedAction(10)
dispatchAsync {
self.store.dispatch(firstAction)
}

dispatchAsync {
self.store.dispatch(secondAction)
}

XCTAssertFalse(secondAction.called)
waitFor { firstAction.called == true }

XCTAssertEqual(store.state.testValue, 5)
firstAction.unblock()

waitFor { store.state.testValue == 3 }

waitFor { secondAction.called == true }
secondAction.unblock()

waitFor { store.state.testValue == 10 }
}

/**
Expand Down Expand Up @@ -111,6 +130,17 @@ class StoreDispatchTests: XCTestCase {
}
}
}

func waitFor(timeout: TimeInterval = 1,
file: StaticString = #file,
line: UInt = #line,
block: () -> Bool) {
let maxTime = Date().addingTimeInterval(timeout).timeIntervalSince1970
while Date().timeIntervalSince1970 < maxTime {
if block() { return }
}
XCTFail("Timed out waiting for condition to be true", file: file, line: line)
}
}

// Needs to be class so that shared reference can be modified to inject store
Expand Down
17 changes: 17 additions & 0 deletions ReSwiftTests/TestFakes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ struct SetValueAction: Action {
}
}

class DelayedAction: Action {
var blocked: Bool = true
var called: Bool = false
let value: Int?

func unblock() { blocked = false }

init(_ value: Int) {
self.value = value
}
}

struct SetValueStringAction: Action {

var value: String
Expand Down Expand Up @@ -87,6 +99,11 @@ struct TestReducer {
case let action as SetValueAction:
state.testValue = action.value
return state
case let action as DelayedAction:
action.called = true
while action.blocked { RunLoop.main.run(until: Date()) }
state.testValue = action.value
return state
default:
return state
}
Expand Down