Last active
August 1, 2018 13:30
-
-
Save rockydd/d4c145f0c09439111c9222b82522fda4 to your computer and use it in GitHub Desktop.
simplified ngrx
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 Dispatcher extends Rx.Subject{ | |
dispatch(value : any) : void { | |
this.next(value); | |
} | |
} | |
class Store extends Rx.BehaviorSubject{ | |
constructor( | |
private dispatcher, | |
private reducer, | |
preMiddleware, | |
postMiddleware, | |
initialState = {} | |
){ | |
super(initialState); | |
this.dispatcher | |
.let(preMiddleware) | |
.scan((state, action) => this.reducer(state, action), initialState) | |
.let(postMiddleware) | |
.subscribe(state => super.next(state)); | |
} | |
/* | |
distinctUntilChanged only emits new values when output is distinct, per last emitted value. | |
In the example below, the observable with the distinctUntilChanged operator will emit one less value then the other with only the map operator applied | |
*/ | |
select(key : string) { | |
return this | |
.map(state => state[key]) | |
.distinctUntilChanged(); | |
} | |
//...store implementation | |
const subscriber = store | |
//with distinctUntilChanged | |
.select('person') | |
.subscribe(val => console.log('PERSON WITH DISTINCTUNTILCHANGED:', val)); | |
const subscriberTwo = store | |
//without distinctUntilChanged, will print out extra time | |
.map(state => state.person) | |
.subscribe(val => console.log('PERSON WITHOUT DISTINCTUNTILCHANGED:', val)); | |
//dispatch a few actions | |
dispatcher.dispatch({ | |
type: 'ADD_INFO', | |
payload: { | |
name: 'Brian', | |
message: 'Exploring Reduce!' | |
} | |
}); | |
//person will not be changed | |
dispatcher.dispatch({ | |
type: 'ADD_HOUR' | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment