Skip to content

Instantly share code, notes, and snippets.

@hitrik
Created February 11, 2020 22:53
Show Gist options
  • Save hitrik/0d5710308e876d14b078a9d07e598287 to your computer and use it in GitHub Desktop.
Save hitrik/0d5710308e876d14b078a9d07e598287 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import { render } from 'react-dom';
import {Subject, interval} from "rxjs";
import {takeUntil, tap} from "rxjs/operators";
//hook creates subject that will destroy on unmount component
const useDestroyedSubject = () => {
const subject$ = new Subject();
React.useEffect(() => () => {
console.log("destroy subject");
subject$.next();
subject$.complete();
}, []);
return subject$;
};
const Test= ({setShow}) => {
const [count, setCount] = React.useState(0);
const destroy$ = useDestroyedSubject();
React.useEffect(() => {
const sub = interval(1000).pipe(takeUntil(destroy$), tap(setCount)).subscribe();
return () => {
console.log("subscriber doesn't exist", sub.closed);
}
}, []);
return <div style={{
border: `${count/2}px solid maroon`,
padding: 5
}}>
<p>{count}</p>
<button onClick={() => setShow(false)}>Destroy me</button>
</div>
};
const App = () => {
const [show, setShow] = React.useState(true);
return (
<div>
<p>
Unsubscribe with takeUntil and subject instance created with custom hook
</p>
{show && <Test setShow={setShow} />}
</div>
);
}
render(<App />, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment