# All files service.js

100% Statements 61/61
100% Branches 14/14
100% Functions 5/5
100% Lines 61/61

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
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    621x
    1x
    1x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    43x
    43x
    43x
    25x
    25x
    1x
    1x
    1x
    1x
    1x
    25x
    25x
    2x
    2x
    1x
    1x
    2x
    25x
    25x
    28x
    27x
    27x
    27x
    27x
    28x
    23x
    23x
    23x
    27x
    28x
    3x
    3x
    27x
    25x
    25x
    25x
    25x
    25x
     import { createMachine, transition, runEffects as run, cleanEffects as clean } from './core.js'

    export function createService(machineDescription, context = {}) {
      const machine = createMachine(machineDescription)

      // initial transition
      const [state, effects] = transition(machine, { name: null, context }, { type: null })

      let cbs = []
      let running = true

      const service = {
        machine,
        state,
        prev: null,
        pendingEffects: effects || [],
        runningEffects: [],
        send,
        subscribe,
        stop,
      }

      function runEffects() {
        service.runningEffects = clean(service.runningEffects)
        service.runningEffects = run(service.pendingEffects, service.state, service.send)
      }

      function stop() {
        running = false
        cbs = []
        service.pendingEffects = []
        service.runningEffects = clean(service.runningEffects)
      }

      function subscribe(fn) {
        cbs.push(fn)
        return () => {
          cbs = cbs.filter((f) => f !== fn)
        }
      }

      function send(event) {
        if (!running) return

        service.prev = service.state
        const [state, effects] = transition(service.machine, service.state, event)
        service.state = state
        if (effects) {
          service.pendingEffects = effects
          runEffects()
        }

        for (const cb of cbs) {
          cb(state)
        }
      }

      runEffects()

      return service
    }