1
1
import type { Middleware , Selector , StoreEnhancer } from '@reduxjs/toolkit'
2
- import { BehaviorSubject , distinctUntilChanged , map , type Observable } from 'rxjs'
3
-
4
- import { invariant } from '@/common/utils'
2
+ import { distinctUntilChanged , map , type Observable , ReplaySubject , share , shareReplay } from 'rxjs'
5
3
6
4
import { injectStoreExtension } from '../enhancers/injectStoreExtension'
7
5
import { weakMemo } from './weakMemo'
@@ -13,17 +11,19 @@ interface StateObserver<State> {
13
11
enhancer : StoreEnhancer < { onState : ObserveState < State > } >
14
12
}
15
13
14
+ const BUFFER_SIZE = 1 // latest state only
15
+
16
16
export const createStateObserver = < State > ( ) : StateObserver < State > => {
17
- const NIL = Symbol ( 'NIL' )
18
- const state$ = new BehaviorSubject < State | typeof NIL > ( NIL )
17
+ const state$ = new ReplaySubject < State > ( BUFFER_SIZE )
19
18
20
19
const distinctState$ = state$ . pipe (
21
- map ( ( state ) => ( invariant ( state !== NIL ) , state ) ) ,
22
20
distinctUntilChanged ( ) ,
21
+ shareReplay ( BUFFER_SIZE ) ,
23
22
)
24
23
25
24
const middleware : Middleware < { } , State > = ( api ) => {
26
- state$ . next ( api . getState ( ) )
25
+ const initialState = api . getState ( )
26
+ state$ . next ( initialState )
27
27
28
28
return ( next ) => ( action ) => {
29
29
const result = next ( action )
@@ -33,7 +33,11 @@ export const createStateObserver = <State>(): StateObserver<State> => {
33
33
}
34
34
35
35
const onState : ObserveState < State > = weakMemo ( ( selector ) =>
36
- distinctState$ . pipe ( map ( selector ) , distinctUntilChanged ( ) ) ,
36
+ distinctState$ . pipe (
37
+ map ( selector ) ,
38
+ distinctUntilChanged ( ) ,
39
+ share ( ) ,
40
+ ) ,
37
41
)
38
42
39
43
const enhancer = injectStoreExtension ( ( ) => ( { onState } ) )
0 commit comments