Skip to content

AHABHGK

RxJS 驱动 React

使用 Subject 类似 EventBus 实现数据交互

Rx 实现 Redux

1interface Action<T = any> {
2 type: T,
3}
4interface AnyAction extends Action {
5 [key: string]: any,
6}
7type Reducer<S = any, A extends Action = AnyAction> = (
8 state: S | undefined,
9 action: A
10) => S
11interface Store<S, A extends Action = AnyAction> {
12 getState(): S,
13 dispatch(action: A): A,
14 subscribe(listener: () => void): () => void,
15}
16const createStore = <S, A extends Action>(reducer: Reducer<S, A>, initialState: S): Store<S, A> => {
17 const action$ = new Subject<A>()
18 let currentState = initialState
19 const store$ = action$.pipe(
20 startWith(initialState as unknown as A),
21 scan(reducer),
22 tap((state) => currentState = state),
23 )
24
25 return {
26 getState: () => currentState,
27 dispatch: (action) => {
28 action$.next(action)
29 return action
30 },
31 subscribe: (listener) => {
32 const subscription = store$.subscribe(listener)
33 return () => {
34 subscription.unsubscribe()
35 }
36 }
37 }
38}
39
40const incrAction = {
41 type: 'incr'
42}
43const decrAction = {
44 type: 'decr'
45}
46const initialState = { num: 0 }
47
48type CountActions = typeof incrAction | typeof decrAction
49
50const re = (state = initialState, action: CountActions) => {
51 switch (action.type) {
52 case 'incr':
53 return { num: state.num + 1 }
54 case 'decr':
55 return { num: state.num - 1 }
56 default:
57 return state
58 }
59}
60
61const store = createStore(re, initialState)
62store.subscribe(console.log)
63store.dispatch(incrAction)