[React] Broadcaster + Operator + Listener pattern -- 20. useBroadcaster & useListener Example

To display a sequence of values in React, we can use our mapSequence operator, wrap it around a broadcaster, then pass that new broadcaster into our useBroadcaster we defined. This will demonstrate that any broadcaster we've defined before should work directly inside of React, but also show that we haven't yet handled the "done" scenario inside of our useBroadcaster.

 

broadcaster.js

import { curry } from "lodash"
import React, {useState, useEffect, useCallback} from "react"

export let done = Symbol("done")

export let createTimeout = curry((time, listener) => {
  let id = setTimeout(() => {
    listener(null)
    listener(done)
  }, time)

  return () => {
    clearTimeout(id)
  }
})

export let addListener = curry(
  (selector, eventType, listener) => {
    let element = document.querySelector(selector)
    element.addEventListener(eventType, listener)

    return () => {
      element.removeEventListener(eventType, listener)
    }
  }
)

export let createInterval = curry((time, listener) => {
  let i = 0
  let id = setInterval(() => {
    listener(i++)
  }, time)
  return () => {
    clearInterval(id)
  }
})

//broadcaster = function that accepts a listener
export let merge = curry(
  (broadcaster1, broadcaster2, listener) => {
    let cancel1 = broadcaster1(listener)
    let cancel2 = broadcaster2(listener)

    return () => {
      cancel1()
      cancel2()
    }
  }
)

export let zip = curry(
  (broadcaster1, broadcaster2, listener) => {
    let cancelBoth

    let buffer1 = []
    let cancel1 = broadcaster1(value => {
      buffer1.push(value)
      // console.log(buffer1)
      if (buffer2.length) {
        listener([buffer1.shift(), buffer2.shift()])

        if (buffer1[0] === done || buffer2[0] === done) {
          listener(done)
          cancelBoth()
        }
      }
    })

    let buffer2 = []
    let cancel2 = broadcaster2(value => {
      buffer2.push(value)

      if (buffer1.length) {
        listener([buffer1.shift(), buffer2.shift()])
        if (buffer1[0] === done || buffer2[0] === done) {
          listener(done)
          cancelBoth()
        }
      }
    })

    cancelBoth = () => {
      cancel1()
      cancel2()
    }

    return cancelBoth
  }
)

export let forOf = curry((iterable, listener) => {
  let id = setTimeout(() => {
    for (let i of iterable) {
      listener(i)
    }
    listener(done)
  }, 0)

  return () => {
    clearTimeout(id)
  }
})

export let useBroadcaster = (broadcaster, deps = []) => {
  let [state, setState] = useState(null)
  useEffect(() => {
    broadcaster((value) => {
      if (value === done) {
        return
      }
      setState(value)
    })
  }, deps)
  return state
}

export let useListener = (deps = []) => {
  let listener
  let callbackListener = value => {
    if (typeof value === "function") {
      listener = value
      return
    }
    listener(value)
  }
  return useCallback(callbackListener, deps)
}

 

operator.js:

import { curry } from "lodash"
import { done } from "./broadcasters"

let createOperator = curry(
  (operator, broadcaster, listener) => {
    return operator(behaviorListener => {
      return broadcaster(value => {
        if (value === done) {
          listener(done)
          return
        }

        behaviorListener(value)
      })
    }, listener)
  }
)

export let map = transform =>
  createOperator((broadcaster, listener) => {
    return broadcaster(value => {
      listener(transform(value))
    })
  })

export let filter = predicate =>
  createOperator((broadcaster, listener) => {
    return broadcaster(value => {
      if (predicate(value)) {
        listener(value)
      }
    })
  })

export let split = splitter =>
  curry((broadcaster, listener) => {
    let buffer = []
    return broadcaster(value => {
      if (value === done) {
        listener(buffer)
        buffer = []
        listener(done)
      }
      if (value == splitter) {
        listener(buffer)
        buffer = []
      } else {
        buffer.push(value)
      }
    })
  })

export let hardCode = newValue =>
  createOperator((broadcaster, listener) => {
    return broadcaster(value => {
      listener(newValue)
    })
  })

export let add = initial => broadcaster => listener => {
  return broadcaster(value => {
    listener((initial += value))
  })
}

export let startWhen = whenBroadcaster => mainBroadcaster => listener => {
  let cancelMain
  let cancelWhen

  cancelWhen = whenBroadcaster(whenValue => {
    if (cancelMain) cancelMain()
    cancelMain = mainBroadcaster(value => {
      if (value === done) {
        if (whenValue === done) {
          listener(done)
        }
        return
      }
      listener(value)
    })
  })

  return () => {
    cancelMain()
    cancelWhen()
  }
}

export let stopWhen = whenBroadcaster => mainBroadcaster => listener => {
  let cancelMain = mainBroadcaster(listener)

  let cancelWhen = whenBroadcaster(value => {
    cancelMain()
  })

  return () => {
    cancelMain()
    cancelWhen()
  }
}

export let targetValue = map(event => event.target.value)

export let mapBroadcaster = createBroadcaster => broadcaster => listener => {
  return broadcaster(value => {
    let newBroadcaster = createBroadcaster(value)
    newBroadcaster(listener)
  })
}

export let applyOperator = broadcaster =>
  mapBroadcaster(operator => operator(broadcaster))

export let stringConcat = broadcaster => listener => {
  let result = ""
  return broadcaster(value => {
    if (value === done) {
      listener(result)
      result = ""
      return
    }
    result += value
  })
}

export let repeat = broadcaster => listener => {
  let cancel
  let repeatListener = value => {
    if (value === done) {
      cancel()
      cancel = broadcaster(repeatListener)
      return
    }

    listener(value)
  }
  cancel = broadcaster(repeatListener)

  return cancel
}

export let repeatWhen = whenBroadcaster => broadcaster => listener => {
  let cancel
  let cancelWhen
  let repeatListener = value => {
    if (value === done) {
      cancel()

      cancelWhen = whenBroadcaster(() => {
        cancelWhen()
        cancel = broadcaster(repeatListener)
      })
      return
    }

    listener(value)
  }
  cancel = broadcaster(repeatListener)

  return () => {
    cancel()
    if (cancelWhen) cancelWhen()
  }
}

export let state = broadcaster => listener => {
  let state = 3
  return broadcaster(value => {
    state--
    listener(state)
  })
}

export let doneIf = condition => broadcaster => listener => {
  let cancel = broadcaster(value => {
    listener(value)
    if (condition(value)) {
      listener(done)
      cancel()
    }
  })

  return cancel
}

export let sequence = (...broadcasters) => listener => {
  let broadcaster = broadcasters.shift()
  let cancel
  let sequenceListener = value => {
    if (value === done && broadcasters.length) {
      let broadcaster = broadcasters.shift()
      cancel = broadcaster(sequenceListener)
      return
    }
    listener(value)
  }

  cancel = broadcaster(sequenceListener)

  return () => {
    cancel()
  }
}

export let mapSequence = createBroadcaster => broadcaster => listener => {
  let cancel
  let buffer = []
  let innerBroadcaster
  let innerListener = innerValue => {
    if (innerValue === done) {
      innerBroadcaster = null
      if (buffer.length) {
        let value = buffer.shift()
        if (value === done) {
          listener(done)
          return
        }
        innerBroadcaster = createBroadcaster(value)
        cancel = innerBroadcaster(innerListener)
      }

      return
    }
    listener(innerValue)
  }
  broadcaster(value => {
    if (innerBroadcaster) {
      buffer.push(value)
    } else {
      innerBroadcaster = createBroadcaster(value)
      cancel = innerBroadcaster(innerListener)
    }
  })

  return () => {
    cancel()
  }
}

 

index.js:

import React from "react"
import { render } from "react-dom"

import {
  useBroadcaster,
  useListener,
  forOf,
  createTimeout
} from "./broadcasters"
import {  targetValue, mapSequence, hardCode} from "./operators"

let message = "Hi, my name is Zhen".split(" ")
let delayMessage = value => hardCode(value)(createTimeout(500))
let broadcaster = mapSequence(delayMessage)(forOf(message))

let App = () => {
  let onInput = useListener()
  let state = useBroadcaster(broadcaster)
  return (
    <div>
      <input type="text" onInput={onInput} />
      <br/>
      {state}
    </div>
  )
}

render(<App></App>, document.querySelector("#root"))

 

上一篇:[Javascript] Broadcaster + Operator + Listener pattern -- 26. Share the Same Broadcaster Values Acro


下一篇:[Javascript] Broadcaster + Operator + Listener pattern -- 18. Create a Win Condition with a mapDone