aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/lib/Reaction.ts
blob: d418d8db83cf703acbeadd0cb83c59a88f6ebe64 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { type IReactionDisposer, type IReactionPublic, autorun } from 'mobx';

export default class Reaction {
  public reaction: (r: IReactionPublic) => any;

  private isRunning: boolean = false;

  public dispose?: IReactionDisposer;

  constructor(reaction: any) {
    this.reaction = reaction;
  }

  start(): void {
    if (!this.isRunning) {
      this.dispose = autorun(this.reaction);
      this.isRunning = true;
    }
  }

  stop(): void {
    if (this.isRunning) {
      this.dispose?.();
      this.isRunning = false;
    }
  }
}

export const createReactions = reactions => reactions.map(r => new Reaction(r));