“I was thinking about Flux as a reduce operation over time... your stores, they accumulate state in response to these actions. I was thinking of taking this further. What if your Flux store was not a store but a reducer function?”
- Dan Abramov
“I was thinking about Flux as a reduce operation over time... your stores, they accumulate state in response to these actions. I was thinking of taking this further. What if your Flux store was not a store but a reducer function?”
- Dan Abramov
/* | |
* The reason for this is just a thought exercise | |
* often people(myself super included) are so confused | |
* when trying something new, but breaking it down | |
* to it's simplest existence can be the best way to understand | |
*/ | |
function createStore(reducer, initState) { | |
let state = initState; | |
let subscribers = []; | |
const getState = () => state; | |
const dispatch = action => { | |
state = reducer(state, action); | |
subscribers.forEach((subscriber) => subscriber()); | |
return action; | |
} | |
const subscribe = (listener) => { | |
subscribers.push(listener); | |
return () => { | |
subscribers = subscribers.slice(subscribers.indexOf(listener) + 1, 1); | |
}; | |
} | |
return { | |
dispatch, | |
subscribe, | |
getState | |
} | |
} | |
const initState = { | |
name: "Conor", | |
redux: "awesome" | |
}; | |
const myReducer = (state, action) => { | |
let newState = Object.assign({}, state); | |
switch (action.type) { | |
case "CHANGE_NAME": | |
newState.name = action.name; | |
break; | |
case "CHANGE_REDUX_ADJECTIVE": | |
newState.redux = action.adjective; | |
break; | |
default: | |
//do nothing | |
} | |
return newState | |
}; | |
const store = createStore(myReducer, initState); | |
console.log(store.getState(), "initial state"); | |
const subscriber = store.subscribe(() => { | |
console.log("i'll console state changes twice then unsubscribe so you will not be notified of the third dispatch", store.getState()); | |
}); | |
store.dispatch({ | |
type: "CHANGE_NAME", | |
name: "Conor Hastings" | |
}); | |
store.dispatch({ | |
type: "CHANGE_REDUX_ADJECTIVE", | |
adjective: "great" | |
}); | |
subscriber(); | |
store.dispatch({ | |
type: "CHANGE_NAME", | |
name: "Conor Cool Guy" | |
}); | |
console.log("the state changed but since we unsubscribed the listener above was not notified o the final dispatch", store.getState()); |
RxJS powered state management for Angular applications, inspired by Redux
export class ShopService {
flow$ = this.store.pipe(select(getFlow));
// ...
}
in the template you can unwrap it by the "async" pipe
<suite-shop-card-content [flow]="flow$ | async">
</suite-shop-card-content>