In April we held 2 ‘OnTrack’ sessions to spread the knowledge of programming with RxJS among our NCORE team members. In this blogpost we will take a high-level look at this library.
What are those observable streams I mentioned? Well it can be a lot of things: A stream of data, a stream of input text, a stream of clicks, a stream of scrolls, etc.
Everything in our application that can change over time is a stream.
Why use RxJS?
RxJS has some important advantages:
- Better control over asynchronous code
- Less code
- Cleaner code
- Less complex code
- Less edge cases
However it comes with some disadvantages as well:
- High learning curve.
- Debugging is hard
- Looking at old code or other people’s code is hard
Complex code needs documentation: for other people to understand it and for yourself when you revisit some old code. So to mitigate this disadvantage we will use marble diagrams. A marble diagram represents the different events of a stream over time. Marble diagrams can also represent operations done on these streams.
How to use RxJS?
RxJS provides a large number of operators we can use to manipulate the observable streams and thus providing the logic for our web app. A simple example is pictured in the marble diagram above: If we are only interested in certain events of our stream, we can apply the filter-operator. And the stream will continue with only those events. In the example we only want the events larger than 10.
There are many different kind of operators we can use in RxJS and I’m not going to mention them all. But we can group them in different categories to provide an overview:
Operators used to create new observables.
These are used to transform events of a stream in different kind of events
Filtering operators are used to let some events pass through while stopping others.
These are a bit different. Conditional operators will add events on the completion of a stream based on a certain condition.
Combine multiple observable streams into one.
Used to share a subscription between observables. This will allow you to split a observable into multiple other streams.
- Error handling
Add logic on the error behavior of your streams.
A collection of general useful operators.
Your knowledge of RxJS is directly linked to your understanding of all the different operators and how to com bine them. The high learning curve is therefore directly linked to the high number of different operators. So knowledge sharing, like we did with the ‘OnTrack’ sessions, becomes very important!