Skip to content

Commit 3c9a120

Browse files
committed
chore(core): remove unnecessary observable
1 parent 266d597 commit 3c9a120

File tree

1 file changed

+28
-35
lines changed

1 file changed

+28
-35
lines changed

packages/core/src/internal/useObservable.ts

Lines changed: 28 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,52 @@
11
import { useEffect, useReducer } from "react"
22
import { BehaviorObservable, Action } from "./BehaviorObservable"
33
import { SUSPENSE } from "../SUSPENSE"
4-
import { Observable } from "rxjs"
4+
import { EMPTY_VALUE } from "./empty-value"
55

66
const reducer = (
77
current: { type: Action; payload: any },
88
action: { type: Action; payload: any },
99
) =>
10-
Object.is(current.payload, action.payload) && current.type === action.type
10+
current.type === action.type && Object.is(current.payload, action.payload)
1111
? current
1212
: action
1313

1414
const init = (source$: BehaviorObservable<any>) => source$.getValue()
1515

16-
const defaultSUSPENSE = <T>(source$: Observable<T>) =>
17-
new Observable<T | typeof SUSPENSE>((observer) => {
18-
let isEmpty = true
19-
const subscription = source$.subscribe(
20-
(x) => {
21-
isEmpty = false
22-
observer.next(x)
23-
},
24-
(e) => observer.error(e),
25-
)
26-
27-
if (isEmpty) {
28-
observer.next(SUSPENSE)
29-
}
30-
31-
return subscription
32-
})
33-
3416
export const useObservable = <O>(
3517
source$: BehaviorObservable<O>,
3618
): Exclude<O, typeof SUSPENSE> => {
3719
const [state, dispatch] = useReducer(reducer, source$, init)
3820

3921
useEffect(() => {
40-
const subscription = defaultSUSPENSE(source$).subscribe(
41-
(value) => {
42-
if ((value as any) === SUSPENSE) {
43-
dispatch(source$.getValue())
44-
} else {
45-
dispatch({
46-
type: Action.Value,
47-
payload: value,
48-
})
49-
}
50-
},
51-
(error) =>
22+
const onNext = (value: O | typeof SUSPENSE) => {
23+
if ((value as any) === SUSPENSE) {
24+
dispatch(source$.getValue())
25+
} else {
5226
dispatch({
53-
type: Action.Error,
54-
payload: error,
55-
}),
27+
type: Action.Value,
28+
payload: value,
29+
})
30+
}
31+
}
32+
const onError = (error: any) =>
33+
dispatch({
34+
type: Action.Error,
35+
payload: error,
36+
})
37+
38+
let val: O | typeof SUSPENSE = SUSPENSE
39+
let err: any = EMPTY_VALUE
40+
let subscription = source$.subscribe(
41+
(v) => (val = v),
42+
(e) => (err = e),
5643
)
44+
if (err !== EMPTY_VALUE) return onError(err)
45+
onNext(val)
46+
const t = subscription
47+
subscription = source$.subscribe(onNext, onError)
48+
t.unsubscribe()
49+
5750
return () => subscription.unsubscribe()
5851
}, [source$])
5952

0 commit comments

Comments
 (0)