types#Watch TypeScript Examples

The following examples show how to use types#Watch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocStore.ts    From core with MIT License 5 votes vote down vote up
compute = (subtree: string, computeCallback: ComputeCallback) => {
    let oldDispose: any;
    const watch: Watch = (
      watchPath: string,
      depth: number = 1,
      firstWatch: boolean = false
    ) => {
      if (oldDispose) {
        oldDispose();
      }

      if (!firstWatch) {
        this.postObserve(() => {
          // postObserve bcoz otherwise a new observer gets added to the end of the array when calling
          // a previous observer leading to an infinite loop
          // console.log('$$$$compute observer 1');
          const dispose = this.observe(
            subtree,
            watchPath,
            (updatedValue, change) => {
              oldDispose = dispose;
              computeCallback(getValue, change);
            },
            depth
          );
        });
      } else {
        // console.log('$$$$compute observer 2');
        const dispose = this.observe(
          subtree,
          watchPath,
          (updatedValue, change) => {
            oldDispose = dispose;
            computeCallback(getValue, change);
          },
          depth
        );
      }

      // return dispose;
    };

    const getValue = (
      path: string,
      depth: number = 1,
      firstRun: boolean = false
    ) => {
      watch(path, depth, firstRun);
      const [doc, setDoc] = this.useSyncState(subtree, path);
      return doc;
    };

    computeCallback(
      (path: string, depth: number = 1) => getValue(path, depth, true),
      {}
    );

    return () => {
      if (oldDispose) {
        oldDispose();
      }
    };
  };