|
1 | 1 | import { useEffect, useReducer } from "react"
|
2 | 2 | import { BehaviorObservable, Action } from "./BehaviorObservable"
|
3 | 3 | import { SUSPENSE } from "../SUSPENSE"
|
4 |
| -import { Observable } from "rxjs" |
| 4 | +import { EMPTY_VALUE } from "./empty-value" |
5 | 5 |
|
6 | 6 | const reducer = (
|
7 | 7 | current: { type: Action; payload: any },
|
8 | 8 | action: { type: Action; payload: any },
|
9 | 9 | ) =>
|
10 |
| - Object.is(current.payload, action.payload) && current.type === action.type |
| 10 | + current.type === action.type && Object.is(current.payload, action.payload) |
11 | 11 | ? current
|
12 | 12 | : action
|
13 | 13 |
|
14 | 14 | const init = (source$: BehaviorObservable<any>) => source$.getValue()
|
15 | 15 |
|
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 |
| - |
34 | 16 | export const useObservable = <O>(
|
35 | 17 | source$: BehaviorObservable<O>,
|
36 | 18 | ): Exclude<O, typeof SUSPENSE> => {
|
37 | 19 | const [state, dispatch] = useReducer(reducer, source$, init)
|
38 | 20 |
|
39 | 21 | 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 { |
52 | 26 | 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), |
56 | 43 | )
|
| 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 | + |
57 | 50 | return () => subscription.unsubscribe()
|
58 | 51 | }, [source$])
|
59 | 52 |
|
|
0 commit comments