Skip to content

Instantly share code, notes, and snippets.

@theladyjaye
Created March 22, 2017 14:43
Show Gist options
  • Save theladyjaye/5f8ddae0983e227a1b810378c17b0a67 to your computer and use it in GitHub Desktop.
Save theladyjaye/5f8ddae0983e227a1b810378c17b0a67 to your computer and use it in GitHub Desktop.
If I understand it, this is basically all Redux is using RxSwift
import RxSwift
let disposeBag = DisposeBag()
enum FooAction: Action{
case increment(Int)
case decrement(Int)
}
struct FooState {
let count: Int
}
struct AppState{
var foo: FooState
}
func fooReducer(action: Action, state: FooState) -> FooState{
guard let action = action as? FooAction else { return state }
switch action{
case .increment(let value):
return FooState(count: state.count + value)
case .decrement(let value):
return FooState(count: state.count - value)
}
}
let initialState = AppState(
foo: FooState(count: 0)
)
let store = Store<AppState>(
initialState: initialState
){
action, state in
return AppState(
foo: fooReducer(action: action, state: state.foo)
)
}
store.subscribe{
state in
print("The Count: \(state.foo.count)")
}.disposed(by: disposeBag)
store.dispatch(action: FooAction.increment(1))
store.dispatch(action: FooAction.increment(1))
store.dispatch(action: FooAction.increment(1))
// I say basically, because it does more then this to be sure (middleware etc),
// but at the "reduce" things level, I think this covers it.
import Foundation
import RxSwift
let stateQueue = DispatchQueue(label: "com.redux.action")
public protocol Action {}
public final class Store<State>{
let _channelSource = PublishSubject<Action>()
var _channel: Observable<State>!
let _reducer: ((Action, State) -> State)
public init(initialState: State, reducer: @escaping (Action, State) -> State){
_reducer = reducer
initChannel(with: initialState)
}
func initChannel(with initialState: State){
_channel = _channelSource
.asObservable()
.subscribeOn(SerialDispatchQueueScheduler(queue: stateQueue, internalSerialQueueName: ""))
.scan(initialState){
state, action -> State in
return self._reducer(action, state)
}
.observeOn(MainScheduler.instance)
.shareReplayLatestWhileConnected()
}
public func dispatch<T: Action>(action: T){
_channelSource.onNext(action)
}
func subscribe(handler: @escaping (State) -> ()) -> Disposable{
return _channel.subscribe(onNext: handler)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment