This story was also posted on my personal blog.
In this post, I’ll talk about a concrete use case in which Observables turn to be remarkably relevant to make our code cleaner and more maintainable.
Yup! This is kind of a specific example. But it perfectly illustrates issues that would beg you for using Observables.
A barcode scanner simply emulates the keyboard. It reproduces the scanned code, emitting keypress signals, ending with the “Enter” key − which key code is 13.
Let’s say we’re developing an app that allows users to search products from their 16-chars code reference. Rather than typing them by hand, users should be able to use a barcode scanner to trigger the search.
“Just let the user focus the search input, scan and you’re done!”
Sure, it’s native behavior.
But the search feature is contained inside a popup that can be open with a button. And we’ve been told the app should be super-ergonomic! Whenever the user scans a barcode, we should open the popup and fill the input with the scanned code.
Now, the problem is: how do we differentiate a scanned code from other keypress events? Let’s say the user hit a key before scanning the code: we don’t want that key to be part of the scanned code!
We surely need to listen to keypress events… Then we must… remember the key codes, probably using a buffer! If the key pressed is the “Enter” key, fill the input and clean the buffer. Otherwise, add the key to the buffer!
Let’s try this first shot:
Good.
But this is not enough: it doesn’t differentiate scanned codes from regular keypresses!
We know that, if no new keypress is emitted after ~50ms, it’s not a scanned code for sure and we can clean the buffer.
Hmmm… not bad. But there is a subtle bug here: if the code takes more than 50ms to be scanned, it will drop the beginning…
In fact, if a new keypress occurs within 50ms, we should clear the timeout.
Now we’ve got something working.
Let’s take a step back and think: what if we’ve had the full history of keypress events we could manipulate to filter out scanned codes sequences? Would the code be simpler? Let’s figure this out…
For this kind of use cases, I find Observables to be a powerful abstraction to represent our data.
Observables are immutable collections of asynchronous events you can manipulate through operators.
If we use things like map and filter over arrays, then we’re already familiar with that way of thinking.
If Observables are still cryptic for you so far, I’d suggest you to read this excellent introduction to Reactive Programming from André Staltz.
So, instead of responding to each event individually, let’s collect all events into a single stream that we can transform.
The $ sign at the end of the variable name means “Stream”.It’s a convention I use to know the variable I manipulate is an Observable in non-typed languages, just like I’d call elements an array of element, or $header the jQuery representation of the header.
Now we have a stream of key codes. Any time a keypress event occurs, a new event, which value is the corresponding key code, is emitted.
At the end of the process, we’d like to have a stream we can subscribe to. Each event of the stream should represent the scanned code. So we need to make batches of key codes in a way that isolates scanned codes from parasitic keypresses.
To do so, we can buffer our stream using a debounce strategy: when an event occurs, wait 50ms for another one. If another event is emitted within this time frame, wait another 50ms. If no other event occurs within this time frame, make a batch of the passed events.
This is what we want to achieve with the buffer operator
So far, so good!
Now, all we have to do is to filter out batches that don’t look like scanned codes. And we know that a scanned code is a sequence that ends with the “Enter” key.
Finally, let’s subscribe to this stream we have created and execute our callback each time a new event is emitted.
Nothing will happen until we subscribe to the Observable, since they are lazy.
This is a visual illustration of what we did to go from keyCode$ − which was created from keypress events − to keyCodesBuffer$ we subscribed to:
Transforming the stream of key codes into a stream of scanned codes
There are a few things to notice with our final code:
In my opinion, the one difficult thing is to reason with streams and understand how to solve our use case with given operators.
But, I believe this is something that just takes practice 😉