Created
July 28, 2018 16:53
-
-
Save okmanideep/a399c08d2c7b0d374364fdd458ccb265 to your computer and use it in GitHub Desktop.
Kotlin Redux
This file contains hidden or 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 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