1 | import { getAtom, observe } from "mobx";
|
2 | /**
|
3 | * MobX normally suspends any computed value that is not in use by any reaction,
|
4 | * and lazily re-evaluates the expression if needed outside a reaction while not in use.
|
5 | * `keepAlive` marks a computed value as always in use, meaning that it will always fresh, but never disposed automatically.
|
6 | *
|
7 | * @example
|
8 | * const obj = observable({
|
9 | * number: 3,
|
10 | * doubler: function() { return this.number * 2 }
|
11 | * })
|
12 | * const stop = keepAlive(obj, "doubler")
|
13 | *
|
14 | * @param {Object} target an object that has a computed property, created by `@computed` or `extendObservable`
|
15 | * @param {string} property the name of the property to keep alive
|
16 | * @returns {IDisposer} stops this keep alive so that the computed value goes back to normal behavior
|
17 | */
|
18 | /**
|
19 | * @example
|
20 | * const number = observable(3)
|
21 | * const doubler = computed(() => number.get() * 2)
|
22 | * const stop = keepAlive(doubler)
|
23 | * // doubler will now stay in sync reactively even when there are no further observers
|
24 | * stop()
|
25 | * // normal behavior, doubler results will be recomputed if not observed but needed, but lazily
|
26 | *
|
27 | * @param {IComputedValue<any>} computedValue created using the `computed` function
|
28 | * @returns {IDisposer} stops this keep alive so that the computed value goes back to normal behavior
|
29 | */
|
30 | export function keepAlive(_1, _2) {
|
31 | var computed = getAtom(_1, _2);
|
32 | if (!computed)
|
33 | throw new Error("No computed provided, please provide an object created with `computed(() => expr)` or an object + property name");
|
34 | return observe(computed, function () { });
|
35 | }
|