crimx/observable-hooks

Unexpected error when using `useSubscription` for a `Subject`

darkyzhou opened this issue · 1 comments

Minimal codes to reproduce:

export default function App() {
  const { current: someValue$ } = useRef(new Subject<number>());

  useSubscription(someObservable$, someValue$);

  // ...
}

Error:
截屏2023-08-15 11 28 53

Stackblitz URL: https://stackblitz.com/edit/stackblitz-starters-uzyyi8?devToolsHeight=33&file=src%2FApp.tsx

Suspicious cause in use-subscription-internal.ts:

const nextObserver =
  (argsRef.current[1] as PartialObserver<TInput>)?.next ||
  (argsRef.current[1] as ((value: TInput) => void) | null | undefined)
if (nextObserver) {
  // BUG: When argsRef.current[1].next presents, this way of calling the function
  // causes `this` to be missing which Subject's `next` relies heavily on.
  return nextObserver(value)
}

A possible fix, would love to open a PR for this:

const observer = argsRef.current[1];
if (observer && 'next' in observer && typeof observer.next === 'function') {
  return observer.next(value);
}

if (observer) {
  return observer(value);
}
crimx commented

observable-hooks@4.2.3 published.