/* eslint-disable import/prefer-default-export */
import type { IReactionDisposer } from 'mobx';
import { autorun } from 'mobx';

export function makeDisposable(
  createReaction: () => IReactionDisposer,
  mustBeDisposed: () => boolean
) {
  let disposer: IReactionDisposer | undefined;

  function cleanDisposer() {
    disposer = undefined;
  }

  autorun(() => {
    if (mustBeDisposed()) {
      if (disposer !== undefined) disposer();
      cleanDisposer();
    } else {
      disposer = createReaction();
    }
  });
}
