Skip to content

Instantly share code, notes, and snippets.

@okmanideep
Created July 28, 2018 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okmanideep/a399c08d2c7b0d374364fdd458ccb265 to your computer and use it in GitHub Desktop.
Save okmanideep/a399c08d2c7b0d374364fdd458ccb265 to your computer and use it in GitHub Desktop.
Kotlin Redux
class Store<S, A>(initialState: S, private val reducer: (S, A) -> S) {
private val TAG = "Redux"
private val stateProcessor: BehaviorProcessor<S> = BehaviorProcessor.create()
private val eventProcessor: PublishProcessor<Event<S, A>> = PublishProcessor.create()
init {
stateProcessor.onNext(initialState)
}
fun stateObs(): Observable<S> {
return stateProcessor.toObservable()
}
fun subscribeTo(actionsObs: Observable<A>): Disposable {
return actionsObs.subscribe(this::applyAction, Timber.tag(TAG)::e)
}
fun applyAction(action: A) {
val newState = reducer(stateProcessor.value, action)
stateProcessor.onNext(newState)
eventProcessor.onNext(Event(newState, action))
}
fun eventObs(): Observable<Event<S, A>> {
return eventProcessor.toObservable()
}
data class Event<S, A>(val state: S, val action: A)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment