1
- import { useEffect , useState } from "react"
1
+ import { useEffect , useState , useRef } from "react"
2
2
import { SUSPENSE } from "../SUSPENSE"
3
3
import { EMPTY_VALUE } from "./empty-value"
4
4
import { Observable } from "rxjs"
@@ -8,31 +8,32 @@ export const useObservable = <O>(
8
8
getValue : ( ) => O ,
9
9
) : Exclude < O , typeof SUSPENSE > => {
10
10
const [ state , setState ] = useState ( getValue )
11
+ const prevStateRef = useRef < O | ( ( ) => O ) > ( state )
11
12
12
13
useEffect ( ( ) => {
13
- let prevVal : O | typeof SUSPENSE = EMPTY_VALUE
14
14
let err : any = EMPTY_VALUE
15
-
16
- const onNext = ( value : O | typeof SUSPENSE ) => {
17
- if ( value === SUSPENSE ) {
18
- setState ( getValue )
19
- } else if ( ! Object . is ( value , prevVal ) ) {
20
- setState ( value )
21
- }
22
- prevVal = value
23
- }
15
+ let syncVal : O | typeof SUSPENSE = EMPTY_VALUE
24
16
const onError = ( error : any ) => {
25
17
err = error
26
18
setState ( ( ) => {
27
19
throw error
28
20
} )
29
21
}
30
22
31
- let subscription = source$ . subscribe ( onNext , onError )
23
+ let subscription = source$ . subscribe ( ( val ) => ( syncVal = val ) , onError )
32
24
if ( err !== EMPTY_VALUE ) return
33
- if ( prevVal === EMPTY_VALUE ) onNext ( SUSPENSE )
25
+
26
+ const set = ( val : O | ( ( ) => O ) ) => {
27
+ if ( ! Object . is ( val , prevStateRef . current ) ) {
28
+ setState ( ( prevStateRef . current = val ) )
29
+ }
30
+ }
31
+
32
+ if ( syncVal === EMPTY_VALUE ) set ( getValue )
34
33
const t = subscription
35
- subscription = source$ . subscribe ( onNext , onError )
34
+ subscription = source$ . subscribe ( ( value : O | typeof SUSPENSE ) => {
35
+ set ( value === SUSPENSE ? getValue : value )
36
+ } , onError )
36
37
t . unsubscribe ( )
37
38
38
39
return ( ) => subscription . unsubscribe ( )
0 commit comments