First, to understand how React Epic works. I will tell you to forget everything about React, got a blank mind first then start to think. In a pure logic, this is how we define a state machine work:
let counter = 0
let increase = (state, action = 1) => state + action
let decrease = (state, action = 1) => state - action
let reset = (state, action) => 0
But this program cannot run because it doesn't have anything to bind with it. The easiest way is to bind to the console:
function bind(state, reducers) {
function render() {
console.log(state)
}
function setState(func) {
state = func(state)
render(state)
}
const ui = Object.keys(reducers).reduce(
(all, name) =>
Object.assign(all, {
[name](action) {
setState(state => reducers[name](state, action))
}
}),
{}
)
return ui
}
So when we run the program, it will log out the result:
Of course, we can but this seems to not very attractive, there will be some cases that you cannot cover if using thunk only. You need something more consistency and powerful than this. So we come up with another solution: RxJS
let counter$ = new BehaviorSubject(0)
let increase$ = new Subject()
let decrease$ = new Subject()
let reset = new Subject()
To make it easier for you to bind pure logic into RxJS, i provide you with a lift operator. The following lines will demonstrate how it works:
import { lift } from 'react-epic'
lift(
state$,
action$,
(state, action) => state + action
).subscribe(state$)
So the increase, decrease, reset functions will be declare like this: