UNPKG

1.53 kBJavaScriptView Raw
1import { isAction, autorun, action, isObservableArray, runInAction } from "mobx";
2/**
3 * `queueProcessor` takes an observable array, observes it and calls `processor`
4 * once for each item added to the observable array, optionally debouncing the action
5 *
6 * @example
7 * const pendingNotifications = observable([])
8 * const stop = queueProcessor(pendingNotifications, msg => {
9 * // show Desktop notification
10 * new Notification(msg);
11 * })
12 *
13 * // usage:
14 * pendingNotifications.push("test!")
15 *
16 * @param {T[]} observableArray observable array instance to track
17 * @param {(item: T) => void} processor action to call per item
18 * @param {number} [debounce=0] optional debounce time in ms. With debounce 0 the processor will run synchronously
19 * @returns {IDisposer} stops the processor
20 */
21export function queueProcessor(observableArray, processor, debounce) {
22 if (debounce === void 0) { debounce = 0; }
23 if (!isObservableArray(observableArray))
24 throw new Error("Expected observable array as first argument");
25 if (!isAction(processor))
26 processor = action("queueProcessor", processor);
27 var runner = function () {
28 // construct a final set
29 var items = observableArray.slice(0);
30 // clear the queue for next iteration
31 runInAction(function () { return observableArray.splice(0); });
32 // fire processor
33 items.forEach(processor);
34 };
35 if (debounce > 0)
36 return autorun(runner, { delay: debounce });
37 else
38 return autorun(runner);
39}