import React , { useState , Suspense , useEffect , ReactNode , useRef , createContext , useContext , } from "react" ; import { Observable , Subscription } from "rxjs" ; const SubscriptionContext = createContext < Subscription > ( null as any ) ; const { Provider } = SubscriptionContext ; export const useSubscription = ( ) => useContext ( SubscriptionContext ) ; const p = Promise . resolve ( ) ; const Throw = ( ) => { throw p ; } ; param source$ param fallback remarks export const Subscribe = ( { source$ , children , fallback } ) => { const subscriptionRef = useRef < Subscription > ( ) ; if ( ! subscriptionRef . current ) { subscriptionRef . current = new Subscription ( ) ; } const [ subscribedSource , setSubscribedSource ] = useState < Observable < any > | null | undefined > ( null ) ; if ( subscribedSource !== null && subscribedSource !== source$ ) { if ( source$ === undefined ) { setSubscribedSource ( source$ ) ; } else { let result ; try { ; ( source$ as any ) . gV ( ) ; result = source$ ; } catch ( e ) { result = e . then ? source$ : null ; } if ( result ) { setSubscribedSource ( result ) ; } } } useEffect ( ( ) => { const subscription = source$ && source$ . subscribe ( { error : ( e ) => setSubscribedSource ( ( ) => { throw e ; } ) , } ) ; setSubscribedSource ( source$ ) ; return ( ) => { subscription && subscription . unsubscribe ( ) ; } ; } , [ source$ ] ) ; useEffect ( ( ) => { return ( ) => { subscriptionRef . current ! . unsubscribe ( ) ; } ; } , [ ] ) ; const actualChildren = subscribedSource === source$ ? ( < Provider value = { subscriptionRef . current ! } > { children } < /Provider>) : fallback === undefined ? null : (<Throw / > ) ; return fallback === undefined ? ( actualChildren ) : ( < Suspense fallback = { fallback } > { actualChildren } < /Suspense>); } ;