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

To build out our word game, we will have to be able to share the word across a few places. This means we have to set up a broadcaster that will push the same values to multiple listeners instead of different values each time a listener is added. We will do this by creating a share operator that can capture the broadcaster and track all of the listeners so that we can hook them together and customize how values get pushed down into the listener callbacks.

 

If we use the same broadcaster twice, we will get two different result.
import React from "react"
import { render } from "react-dom"

import {
  useBroadcaster,
  getUrl,
} from "./broadcasters"
import {map} from "./operators"
import {pipe} from "lodash/fp"
import { head } from "lodash"
  
let getWord = pipe(
  map(head),
)(getUrl('https://random-word-api.herokuapp.com/word'))

let App = () => {

  let word = useBroadcaster(getWord)
  let anotherWord = useBroadcaster(getWord)
  return (
    <div>
      <p>{word}</p>
      <p>{anotherWord}</p>
    </div>
  )
}

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

So 'getWord' function will send two network requests.

 

The setup 'share' logic, so broadcaster will send the same value to multipule listeners:

let share = () => {
  let listeners = [];
  let cancel;
  return broadcaster => {
    cancel = broadcaster(value => {
      listeners.forEach(l => l(value))
    });
    return listener => {
      listeners.push(listener);
      return () => {
        cancel()
      }
    }
  }
}

 

Using it:

let getWord = pipe(
  map(head),
  share()
)(getUrl('https://random-word-api.herokuapp.com/word'))

 

--

 

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

import {
  useBroadcaster,
  getUrl,
} from "./broadcasters"
import { map, filter} from "./operators"
import {pipe} from "lodash/fp"
import { head } from "lodash"

let share = () => {
  let listeners = [];
  let cancel;
  return broadcaster => {
    // this block of code will run last
    cancel = broadcaster(value => {
      listeners.forEach(l => l(value))
    });
    return listener => {
      // this block of code will run mult times
      listeners.push(listener);
      return () => {
        cancel()
      }
    }
  }
}
  
let getWord = pipe(
  map(head),
  share()
)(getUrl('https://random-word-api.herokuapp.com/word'))

let App = () => {

  let word = useBroadcaster(getWord)
  let anotherWord = useBroadcaster(getWord)
  let anotherWord2 = useBroadcaster(getWord)
  return (
    <div>
      <p>{word}</p>
      <p>{anotherWord}</p>
    </div>
  )
}

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

  

上一篇:Eclipse git提交项目到本地仓库时报错Unable to find a GPG key for signing


下一篇:[React] Broadcaster + Operator + Listener pattern -- 20. useBroadcaster & useListener Example