Reputation: 703
What role do Observables play in implementing the redux library?
I have always wondered how actions communicate with reducers. When writing code, these functions don't call each other. (This is the most confusing part)
I can tell they are connected via types, what is the role of these types in making the redux library work?
How does this pattern look diagrammatically? It will be helpful to wrap my head around this. Just the redux design no react or any other library or framework.
I am seeking to understand the underlying mechanisms of the library, not how to use it
Thank you.
Upvotes: 0
Views: 338
Reputation: 67577
Redux has nothing to do with observables as such.
A basic Redux store implementation looks like this:
function createStore(reducer, preloadedState) {
let state = preloadedState
const listeners = []
function getState() {
return state
}
function subscribe(listener) {
listeners.push(listener)
return function unsubscribe() {
const index = listeners.indexOf(listener)
listeners.splice(index, 1)
}
}
function dispatch(action) {
state = reducer(state, action)
listeners.forEach(listener => listener())
}
dispatch({ type: '@@redux/INIT' })
return { dispatch, subscribe, getState }
}
Calling store.dispatch(action)
causes the store to run state = reducer(state, action)
. There really is only that one "root reducer" function. But, we typically implement that root reducer by splitting it up into many smaller "slice reducer" functions to do the work, which makes it more maintainable.
So, in the end it's "just" a series of normal function calls:
store.dispatch(action)
reducer(state, action)
postsReducer(state.posts, action)
Having said all that, the Redux store can be treated as an observable itself, and other observables can listen for updates to the state. But no observables are used in the actual implementation.
Upvotes: 2