Skip to content

Commit

Permalink
fix(bind): supports observables of functions
Browse files Browse the repository at this point in the history
  • Loading branch information
voliva authored and josepot committed Jan 7, 2021
1 parent 615e469 commit 30501dd
Showing 1 changed file with 4 additions and 10 deletions.
14 changes: 4 additions & 10 deletions packages/core/src/internal/useObservable.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { useEffect, useState, useRef } from "react"
import { useEffect, useState } from "react"
import { Observable } from "rxjs"
import { SUSPENSE } from "../SUSPENSE"
import { EMPTY_VALUE } from "./empty-value"
import { Observable } from "rxjs"

export const useObservable = <O>(
source$: Observable<O>,
getValue: () => O,
keys: Array<any>,
): Exclude<O, typeof SUSPENSE> => {
const [state, setState] = useState(getValue)
const prevStateRef = useRef<O | (() => O)>(state)

useEffect(() => {
let err: any = EMPTY_VALUE
Expand All @@ -27,19 +26,14 @@ export const useObservable = <O>(
}, onError)
if (err !== EMPTY_VALUE) return

const set = (value: O | (() => O)) => {
if (!Object.is(prevStateRef.current, value))
setState((prevStateRef.current = value))
}

const defaultValue = (getValue as any).d
if (syncVal === EMPTY_VALUE) {
set(defaultValue === EMPTY_VALUE ? getValue : defaultValue)
setState(defaultValue === EMPTY_VALUE ? getValue : () => defaultValue)
}

const t = subscription
subscription = source$.subscribe((value: O | typeof SUSPENSE) => {
set(value === SUSPENSE ? getValue : value)
setState(value === SUSPENSE ? getValue : () => value)
}, onError)
t.unsubscribe()

Expand Down

0 comments on commit 30501dd

Please sign in to comment.