Combine Broadcasters in Logical Order

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

You often want one broadcaster to set up another broadcaster so that the second one waits for the first one to fire off the value. In our situation, we want the word to load before we start accepting values from the input field because guessing a word before a word loads doesn't make any sense. This also forced us into using React's system of useEffect and dependencies rather than our library of broadcasters and operators To manage when broadcasters repeat. We gain much more control when we use our own operators to handle when broadcasters push new values.

John Lindquist: [0:00] Unfortunately, we still have one major bug here due to how useEffect works inside of React. In our useBroadcaster, useEffect expects us to return a way to cancel or tear down what's going on inside of it.

[0:17] We built our broadcasters in such a way that we get a cancel function. Let's grab that and we can return a function that calls our cancel function. This satisfies useEffect. You'll notice once I start typing reposes that nothing happens here. That's because useEffect is called every time a dependency changes.

[0:45] Back in our Index, where the word starts as an empty string and then changes to a word like reposes, then our useEffect calls cancel that second time around, which cancels our broadcaster and stops it from working.

[1:01] Rather than relying on watching a dependency like wordToChange instead of useEffect again, let's delete that and move that logic into here. I'm going to call this thenCombine, meaning that we'll take our word, so we'll get word, and then we'll combine it with guess broadcaster, setting up the same logic we had before here, but now with more control over it inside of our own operators and broadcasters.

[1:31] A thenCombine would look something like this, where we set up a thenCombine. This would take a second broadcaster. This is going to return mapBroadcaster. Let's import that, and mapBroadcaster will be taking values from the first broadcaster, so in our case, this is the word, but I'm going to name it generically as firstValue.

[1:58] Then we're going to map this to the second broadcaster, and we'll wrap this inside of a map that maps together the second value into an array, and I'm going to map this as firstValue and secondValue, so it'll look like this, firstValue and secondValue. To fix this, let's swap the order here. We'll put word first and guess second.

[2:27] Now when I type something, [inaudible] this is. We're back to working on the surface with just a couple of minor issues underneath.