Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Created January 10, 2016 18:00
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ben-G/c33486169d68a6f3d12f to your computer and use it in GitHub Desktop.
Save Ben-G/c33486169d68a6f3d12f to your computer and use it in GitHub Desktop.
Swift Flow + RxSwift
class RxObserver<T>: StoreSubscriber {
var state: Variable<T?> = Variable(nil)
private var store: MainStore
init(store: MainStore) {
self.store = store
self.store.subscribe(self)
}
deinit {
self.store.unsubscribe(self)
}
func newState(newState: AppState) {
state.value = newState as? T
}
}
// Reducer and action for testing:
struct AppState: StateType {
var number: Int = 3
}
struct IncAction: Action {}
struct MyReducer: Reducer {
func handleAction(state: AppState, action: Action) -> AppState {
return AppState(number: state.number+1)
}
}
// Then set up as following:
let store = MainStore(reducer: MyReducer(), appState: AppState())
let rx = RxObserver<AppState>(store: store)
// Then subscribe:
let _ = rx.state.asObservable().subscribeNext { state in
print(state)
}
store.dispatch(IncAction())
store.dispatch(IncAction())
store.dispatch(IncAction())
store.dispatch(IncAction())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment