RxJS Basics
Updated: 27 October 2023
- RxJS Website
- RxJS Examples and Operators
- DesignCourse on Youtube
- Laith Academy on Youtube
- RxJS Marbles
Overview
- RxJS is an implementation of ReactiveX in js
- ReactiveX is a way of programming with observable streams
“ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming” ~ ReactiveX
Installation
- Create a new typescript static site project:
And select ts-static
- Add
rxjs
- Start the site
Importing RxJS
To import something from RxJS from the index.ts
file you can use the following:
This should log the Observable
object from RxJS
Observables
A stream is a series of events that are emitted over time. An observable provides a means to emit and respond to stream events
Create an Observable
We can create an observable that emits string
values with the following:
Subscribe to an Observable
However, we won’t see events emitted unless we have observers
, in order to get the value we need to define an observer by with the subscribe
method. In this case due to how the observable was defined the value
will be of type string
:
Observable Events
The events that we can respond to on an observable are next
, error
, and complete
We can additionally also handle errors and completion events by passing them into the subscribe as additional params:
Unsubscribe
To unsubscribe you can use the observer.unsubscribe
method:
Multiple Observers
We can create multiple observers simply by using the observable.subscribe
method:
Child Subscriptions
If we want to create linked/child observers we can call the observer.add
and observer.remove
methods to add new observers instead of the observable.subscribe
which will ensure that the child observers are unsubscribed when the parent is:
In the below, the child will not unsubscribe as it’s removed from the parent:
However, if we don’t remove it, it will automatically
Hot or Cold
A cold observable is an observable whose producer is only activated once a subscription has been created
For example, we can create a second observer after a second, this observer will receive all the messages from the start but they will come through a second delayed:
However, if we want our observer to get the latest updates and not receive older messages we can create a warm/hot observer by piping the share
method when we define our observable, this will ensure that the observer created above will receive the latest messages only
Now, the observerLate
will only print out from tick 2
instead of all the ticks
From Event
You can create an observable from DOM events by using the fromEvent
function:
Subjects
A subject is simultaneously an observer and an observable which means we are able to send events using the subject and are also able to subscribe to the subject
So now we can add observers and send new messages like this:
In the above, observer2
will only react to the second message
There are four types of subjects:
Normal Subject
A Normal
subject will allow observers to only receive events received after it subscribed, this is what was used above as well:
Behavior Subject
A Behavior
subject will allow observers to receive all events received after it subscribed as well as:
- An initial event for the first observer only
- The last event fired before a new observer subscribes
In the above, observer1
gets the welcome
event as well as the first
, second
, and third
messages, and observer2
gets the second
and third
messages only even though the second
message was fired before observer2
subscribed
Replay Subject
A Replay
subject allows you to specify a buffer of events that should be replayed to new subscribers
So in the above, observer2
will receive the second
, third
, and fourth
messages only
Additionally a Replay
subject can accept a second optional argument when constructing which is a buffer time in which the events should be replayed. Any events that happen outside of this timeframe will not be replayed
In the above, observer2
will receive ticks 4
and 5
even though it only starts listening at tick 6
. The observer receives a time-based buffer of messages - 200ms
in this case - and not a count-based one. The 20
provided to the ReplaySubject
constructor is the max number of messages that should be bufferred
Async Subject
The async subject only emits the last value and will only do so once the complete
method has been called on the subject
In the above example, the observer
will only receive the final result
once the .complete
method is called on the subject, kind of like a promise where there is only one actual result
Operators
Lots of operators, these can be understood using Marble Diagrams
Operators are pure functions that do not modify the observable but will create a new observable
There are two types of operators
- Static operators - Used to create observables
- Instance operators - Methods on Observable Instances
Marble Diagrams
Marble diagrams show us how an operator applies to the observable stream over time
X
represents an error|
represents an observable completion
Using Operators
Merge Operator
Used to merge the results from two different observables. This will combine the results from two observables into a single observable
The mergedObservable
will log the data that is emitted from both the observables
Map Operator
The Map Operator can be used to transform the data from the observable
In the above, we use map
to create an observable operator that can be used to get the length of the message passed. In this example we will just log out the lengths of each message, 10
and 17
respectively
SkipUntil
Allows us to emit events from one observable until a second one starts emitting events