Published
Edited
Aug 23, 2018
8 stars
Insert cell
Insert cell
Insert cell
Insert cell
function RxReduxStore(initial_state, reducers) { // pass in state and action functions
let streams = {}, actions = {}, store$
for (let action in reducers) { // pass in reducers keyed by action name
let subject$ = new Rx.Subject() // subject for action/reducer data flow
streams[`${action}$`] = subject$.map(reducers[action]) // stash a reducer mapped to a stream
actions[action] = (args) => subject$.next(args) // forward action params to reducer stream
}

store$ = new Rx.BehaviorSubject(initial_state) // main store stream seeded with state
.merge(...Object.values(streams)) // merge all reducers into single stream
.scan((state, reducer) => reducer(state)) // pass state to each reducer
return {store$, actions} // return store observable and action streams
}
Insert cell
Insert cell
CountStore = RxReduxStore(0, {
increment: (amount = 1) => count => count + amount,
decrement: (amount = 1) => count => count - amount,
})
Insert cell
Insert cell
Insert cell
Insert cell
ActionBreakdown = {
// shorthand ES6
var increment = (amount = 1) => count => count + amount
// could also be written as
var increment = function(amount = 1) {
return function(count) {
return count + amount
}
}
}
Insert cell
Insert cell
TodosStore = RxReduxStore([], {
create: new_todo => todos =>
[...todos, new_todo],
update: updated_todo => todos => todos.map(datum =>
datum.id === updated_todo.id
? Object.assign(datum, updated_todo)
: datum),
delete: poor_todo => todos => todos.filter(datum =>
datum.id !== poor_todo.id),
})
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Logger('Todos', TodosStore.store$)
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more