Skip to content

Redux-inspired state management for Swift

License

Notifications You must be signed in to change notification settings

YodelTalk/Recombine

Repository files navigation

Recombine

Our take on a Redux-inspired state management for Swift.

Installation (via SPM)

In your Package.swift add the following:

dependencies: [
  .package(url: "https://github.com/YodelTalk/Recombine.git", .branch("main"))
]

Usage

import Recombine

struct State: Changeable {
  var counter = 0
}

enum Action {
  case increase
  case decrease
}

typealias AppStore = Store<Action, State>

func counterReducer(action: Action, state: State) -> State {
  switch action {
  case .increase:
    return state.changed(\.counter, to: state.counter + 1)
  case .decrease:
    return state.changed(\.counter, to: state.counter - 1)
  }
}

let logger = { (dispatch: @escaping AppStore.Dispatch, store: AppStore) in
  return { (action: Action) in
    print("Handling action: \(action)")
    dispatch(action)
    print("New state: \(store.counter)")
  }
}

let store = AppStore(
  initialState: State(),
  reducers: [counterReducer],
  middlewares: [logger]
)

store.dispatch(.increase)
store.dispatch(.decrease)
store.dispatch(.decrease)

store.counter // -1

Inspiration

License

The MIT License