Created
January 10, 2016 18:00
-
-
Save Ben-G/c33486169d68a6f3d12f to your computer and use it in GitHub Desktop.
Swift Flow + RxSwift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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