xref: /aosp_15_r20/external/perfetto/ui/src/base/monitor.ts (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1// Copyright (C) 2024 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15type Reducer = () => unknown;
16type Callback = () => void;
17
18/**
19 * A little helper that monitors a list of immutable objects and calls a
20 * callback only when at least one them changes.
21 */
22export class Monitor {
23  private cached: unknown[];
24
25  constructor(private reducers: Reducer[]) {
26    this.cached = reducers.map(() => undefined);
27  }
28
29  /**
30   * Invokes all reducers and compares values against with the previous values.
31   *
32   * If any of the values have changed, |callback| is called (if present) and
33   * returns true, otherwise no callback is called and returns false.
34   *
35   * @param callback Optional callback to call when diffs are detected.
36   * @returns True if diffs were detected, false otherwise.
37   */
38  ifStateChanged(callback?: Callback): boolean {
39    const oldState = this.cached;
40    const newState = this.reducers.map((f) => f());
41    this.cached = newState;
42    if (newState.some((x, i) => x !== oldState[i])) {
43      callback?.();
44      return true;
45    }
46
47    return false;
48  }
49}
50