Angular Concepts in React: The Async Pipe

Esteban Hernández on September 14, 2019

One of my favorite tools in the Angular framework is the Async pipe. It allows me to render the latest value of an Observable to the screen. The co... [Read Full]
markdown guide
 

You could also create a custom hook for this pattern. I have one called useRxjs.

import { some, none, fromNullable } from 'fp-ts/lib/Option';
import { Observable } from 'rxjs'
import { useEffect, useState } from 'react'

const useRxjs = <T>(obs: Observable<T>, init?: T) => {
  const [state, setState] = useState(fromNullable(init));
  const [errorState, setErrorState] = useState(none);
  const [completeState, setCompleteState] = useState(false);

  useEffect(() => obs
    .subscribe(
      n => setState(some(n)),
      e => setErrorState(some(e)),
      () => setCompleteState(true),
    ).unsubscribe, [obs, init]);
  return [state, errorState, completeState];
}
 

Why does the return function unsubscribe?

 

The useEffect hook can optionally return a 'clean-up' function which will be called once the input, in this case the 'ticker' observable changes or if the component unmounts. So, if our Observable where to change then we'd unsubscribe from the first one before subscribing to the new one.

code of conduct - report abuse