Reactive Programming is gaining momentum
these days and here is my minimal contribution to get more people interested,
which hopefully will rise average software products quality in “The Industry”.
This is part 1 of “Reactive traffic lights” series where I’m going
to build automated traffic lights
It’s just a “case-study”
so you’re always welcome to comment on things may be done better
or more idiomatic way.
Let’s list some basic requirements:
- There must be 2 automatic lights: for cars and for pedestrians;
- Lights for cars have 3 colors: red, yellow, green;
- Pedestrian lights have 2 colors: red and green;
- Green light should blink before switch.
We will “render” our traffic lights using simple blocks with circles inside:
The only dependency we have - is Rx library:
First - lets build default static version where cars light is always green.
As pedestrians light is simpler: have only 2 colors excluding each other
- we can define it depending on cars light.
Now green light for cars must be lighter and same for pedestrians red.
React to time
Now let’s make it work, based on a timer
Define the timer
Timer is the single signal sources needed for this case, other values will be derived from it.
Green for vehicles will be on first 32 ticks, next 5 - will blink
and next 3 - yellow will be on:
Yellow will be on last 3 ticks for both - vehicles and pedestrians periods:
Red - on for full pedestrian period:
Pedestrian green is on while red for vehicles and is blinking last 5 ticks:
Pedestrian red is opposite to green:
Additionally let’s add some countdowns. As our timer is running twice a second
we will round our countdown to seconds dividing by 2:
And finally - connect all dots:
By defining our problems as signal streams and transformations it becomes
really easy to compose the solution using great libraries like RxJs.
Of course being reactive means much more than we seen in this simple example,
and I highly recommend you go deeper.
In the next “episode” I’m planning to transform this example to a