All files / src/utils/unwatch unwatch.ts

100% Statements 7/7
100% Branches 0/0
100% Functions 1/1
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 309x                                         9x 7x 7x 7x 7x   7x    
import { scope } from '../../constants'
 
/**
 * **Disables automatic state subscriptions** by wrapping value access in `unwatch`.
 *
 * **Unlike `callEvent`/`createEvent`**, `unwatch` does **NOT batch updates**.
 *
 * ```ts
 * import { State, Watch, unwatch } from 'watch-state'
 *
 * const count = new State(0)
 *
 * new Watch(() => {
 *   console.log(unwatch(() => count.value++))
 * })                       // logs: 0
 *
 * count.value++            // logs: 1
 *
 * console.log(count.value) // logs: 2
 * ```
 * */
export function unwatch<T> (fn: () => T): T {
  const { activeWatcher } = scope
  scope.activeWatcher = undefined
  const result = fn()
  scope.activeWatcher = activeWatcher
 
  return result
}