Rxjs Tutorial
Rxjs Tutorial
i
RxJS
Audience
This tutorial is designed for software programmers who want to learn the basics of Reactive
extension for Javascript (RxJS) and its programming concepts in simple and easy way.
This tutorial will give you enough understanding on various functionalities of RxJS with
suitable examples.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of Javascript.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
ii
RxJS
Table of Contents
About the Tutorial ........................................................................................................................................... ii
Audience .......................................................................................................................................................... ii
Prerequisites .................................................................................................................................................... ii
iii
RxJS
ajax ................................................................................................................................................................ 26
from ............................................................................................................................................................... 27
fromEvent ...................................................................................................................................................... 28
fromEventPattern .......................................................................................................................................... 29
interval........................................................................................................................................................... 30
of.................................................................................................................................................................... 30
range.............................................................................................................................................................. 31
throwError ..................................................................................................................................................... 32
timer .............................................................................................................................................................. 33
iif .................................................................................................................................................................... 34
count.............................................................................................................................................................. 35
max ................................................................................................................................................................ 36
min ................................................................................................................................................................. 37
Reduce ........................................................................................................................................................... 38
concat ............................................................................................................................................................ 39
forkJoin .......................................................................................................................................................... 40
merge ............................................................................................................................................................ 41
race ................................................................................................................................................................ 41
iv
RxJS
buffer ............................................................................................................................................................. 42
bufferCount ................................................................................................................................................... 43
bufferTime ..................................................................................................................................................... 45
bufferToggle .................................................................................................................................................. 46
bufferWhen ................................................................................................................................................... 47
expand ........................................................................................................................................................... 48
groupBy ......................................................................................................................................................... 49
map ................................................................................................................................................................ 50
mapTo ............................................................................................................................................................ 51
mergeMap ..................................................................................................................................................... 52
switchMap ..................................................................................................................................................... 53
window .......................................................................................................................................................... 53
debounce ....................................................................................................................................................... 54
debounceTime ............................................................................................................................................... 55
distinct ........................................................................................................................................................... 56
elementAt ...................................................................................................................................................... 57
filter ............................................................................................................................................................... 58
first ................................................................................................................................................................ 59
last ................................................................................................................................................................. 59
ignoreElements.............................................................................................................................................. 60
sample ........................................................................................................................................................... 61
skip ................................................................................................................................................................ 62
throttle .......................................................................................................................................................... 62
tap ................................................................................................................................................................. 63
delay .............................................................................................................................................................. 64
delayWhen .................................................................................................................................................... 65
subscribeOn ................................................................................................................................................... 67
timeInterval ................................................................................................................................................... 68
v
RxJS
timestamp ..................................................................................................................................................... 69
timeout .......................................................................................................................................................... 70
toArray........................................................................................................................................................... 71
defaultIfEmpty ............................................................................................................................................... 72
every .............................................................................................................................................................. 72
find................................................................................................................................................................. 73
findIndex ........................................................................................................................................................ 74
isEmpty .......................................................................................................................................................... 75
multicast ........................................................................................................................................................ 75
publish ........................................................................................................................................................... 77
publishBehavior ............................................................................................................................................. 78
publishLast ..................................................................................................................................................... 79
publishReplay ................................................................................................................................................ 80
share .............................................................................................................................................................. 81
catchError ...................................................................................................................................................... 82
retry ............................................................................................................................................................... 83
AsyncSubject ................................................................................................................................................. 93
vi
1. RxJS — Overview RxJS
This chapter deals with information about features, advantages and disadvantages of
RxJS. Here, we will also learn when to use RxJS.
The full form of RxJS is Reactive Extension for Javascript. It is a javascript library that
uses observables to work with reactive programming that deals with asynchronous data
calls, callbacks and event-based programs. RxJS can be used with other Javascript libraries
and frameworks. It is supported by javascript and also with typescript.
What is RxJS?
As per the official website of RxJS, it is defined as a library for composing asynchronous
and event-based programs by using observable sequences. It provides one core type, the
Observable, satellite types (Observer, Schedulers, Subjects) and operators inspired by
Array#extras (map, filter, reduce, every, etc.) to allow handling asynchronous events as
collections.
Features of RxJS
In RxJS, the following concepts takes care of handling the async task:
Observable
An observable is a function that creates an observer and attaches it to the source where
values are expected, for example, clicks, mouse events from a dom element or an Http
request, etc.
Observer
It is an object with next(), error() and complete() methods, that will get called when there
is interaction to the with the observable i.e. the source interacts for an example button
click, Http request, etc.
Subscription
When the observable is created, to execute the observable we need to subscribe to it. It
can also be used to cancel the execution.
Operators
An operator is a pure function that takes in observable as input and the output is also an
observable.
Subject
A subject is an observable that can multicast i.e. talk to many observers. Consider a button
with an event listener, the function attached to the event using addlistener is called every
time the user clicks on the button similar functionality goes for subject too.
1
RxJS
Schedulers
A scheduler controls the execution of when the subscription has to start and notified.
RxJS can be used with other Javascript libraries and frameworks. It is supported
by javascript and also with typescript. Few examples are Angular, ReactJS, Vuejs,
nodejs etc.
RxJS is an awesome library when it comes to the handling of async tasks.RxJS uses
observables to work with reactive programming that deals with asynchronous data
calls, callbacks and event-based programs.
As you start to use Observables, you can end up your full code wrapped under the
observables.
2
2. RxJS ― Environment Setup RxJS
In this chapter, we are going to install RxJS. To work with RxJS, we need the following
setup:
NodeJS
Npm
RxJS package installation
In case you are getting the version, it means nodejs and npm is installed on your system
and the version is 10 and 6 right now on the system.
If it does not print anything, install nodejs on your system. To install nodejs, go to the
homepage https://nodejs.org/en/download/ of nodejs and install the package based on
your OS.
3
RxJS
Based on your OS, install the required package. Once nodejs is installed, npm will also be
installed along with it. To check if npm is installed or not, type npm –v in the terminal. It
should display the version of the npm.
Once the folder rxjsproj/ is created, run command npm init, for project setup as shown
below:
E:\>mkdir rxjsproj
E:\>cd rxjsproj
E:\rxjsproj>npm init
Npm init command will ask few questions during execution, just press enter and proceed.
Once the execution of npm init is done, it will create package.json inside rxjsproj/ as
shown below:
rxjsproj/
package.json
4
RxJS
+ [email protected]
added 2 packages from 7 contributors and audited 2 packages in 21.89s
found 0 vulnerabilities
We are done with RxJS installation. Let us now try to use RxJS, for that create a folder
src/ inside rxjsproj/
rxjsproj/
node_modules/
src/
package.json
Inside src/ create a file testrx.js, and write the following code:
testrx.js
When we go to execute the above code in command prompt, using command: node
testrx.js, it will display error for import, as nodejs does not know what to do with import.
To make import work with nodejs, we need to install ES6 modules package using npm as
shown below:
5
RxJS
+ [email protected]
added 1 package from 1 contributor and audited 3 packages in 9.32s
found 0 vulnerabilities
Once the package is installed, we can now execute testrx.js file as shown below:
We can see the output now, that shows RxJS is installed and ready to use. The above
method will help us test RxJS in the command line. In case, you want to test RxJS in the
browser, we would need some additional packages.
+ [email protected]
+ [email protected]
+ @babel/[email protected]
6
RxJS
+ @babel/[email protected]
+ [email protected]
+ [email protected]
added 675 packages from 373 contributors and audited 10225 packages in 255.567s
found 0 vulnerabilities
To start the server to execute our Html file, we will use webpack-server. The command
"publish" in package.json will help us start as well as pack all the js files using webpack .
The packed js files which are our final js file to be used is saved at the path /dev folder.
To use webpack, we need to run npm run publish command and the command is added
in package.json as shown below:
Package.json
{
"name": "rxjsproj",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"publish":"webpack && webpack-dev-server --output-public=/dev/",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.6.0",
"@babel/preset-env": "^7.6.0",
"babel-loader": "^8.0.6",
"esm": "^3.2.25",
"rxjs": "^6.5.3",
"webpack": "^4.39.3",
"webpack-cli": "^3.3.8",
7
RxJS
"webpack-dev-server": "^3.8.0"
}
}
To work with webpack we must first create a file called webpack.config.js that has the
configuration details for webpack to work.
module.exports = {
entry: {
app: './src/testrx.js'
},
output: {
path: path.resolve(__dirname, 'dev'),
filename: 'main_bundle.js'
},
mode:'development',
module: {
rules: [
test:/\.(js)$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
query: {
presets: ['@babel/preset-env']
}
}
]
}
};
8
RxJS
The structure of the file is as shown above. It starts with a path that gives the current
path details.
Next is module.exports object which has properties entry, output, and module. Entry is
the start point. Here, we need to give the start js file we want to compile.
entry: {
app: './src/testrx.js'
},
path.resolve(_dirname, ‘src/testrx.js’) -- will look for src folder in the directory and
testrx.js in that folder.
Output
output: {
path: path.resolve(__dirname, 'dev'),
filename: 'main_bundle.js'
},
The output is an object with path and filename details.path will hold the folder in which
the compiled file will be kept and the filename will tell the name of the final file to be used
in your .html file.
Module
module: {
rules: [
{
test:/\.(js)$/,
9
RxJS
Module is object with rules details which has properties i.e. test, include, loader, query.
The test will hold details of all the js file ending with .js and .jsx. It has the pattern which
will look for .js at the end in the entry point given.
The query has property presets which is an array with value '@babel/preset-env’. It will
transpile the code as per the ES environment you need.
rxjsproj/
node_modules/
src/
testrx.js
index.html
package.json
webpack.config.js
Run Command
npm run publish will create dev/ folder with main_bundle.js file in it. The server will be
started and you can test your index.html in the browser as shown below.
10
RxJS
11
3. RxJS6 ― Latest Updates RxJS
We are using RxJS version 6 in this tutorial. RxJS is commonly used to deal with reactive
programming and used more often with Angular, ReactJS. Angular 6 loads rxjs6 by default.
RxJS version 5 was handled differently in comparison to version 6. The code will break in
case you update your RxJS 5 to 6. In this chapter, we are going to see the difference in
ways of handling the version update.
In case you are updating RxJS to 6 and don't want to make the code changes, you can do
that too, and will have to install the following package.
This package will take care of providing backward compatibility and old code will work fine
with RxJS version 6. If you want to make the code changes that works fine with RxJS 6,
here are the changes that needs to be done.
The packages for operators, observables, subject were restructured and hence, the major
changes go in for imports and they are explained below.
import 'rxjs/add/operator/mapTo'
import 'rxjs/add/operator/take'
import 'rxjs/add/operator/tap'
import 'rxjs/add/operator/map'
import "rxjs/add/observable/from";
import "rxjs/add/observable/of";
import "rxjs/add/observable/fromEvent";
import "rxjs/add/observable/interval";
12
RxJS
Import of Observables
In RxJS version 5, while working with Observables, the following import statements should
be included:
Import of Subject
In RxJS version 5, subject should be included as follows:
Example
import "rxjs/add/observable/from";
import 'rxjs/add/operator/max'
From RxJS version 5.5 onwards, we have to use pipe() to execute the operator:
Example
import { from } from 'rxjs';
import { max } from 'rxjs/operators';
13
RxJS
Operators Renamed
During restructuring of the packages some of the operators were renamed as they were
conflicting or matching with javascript keywords. The list is as shown below:
Operator Renamed to
do() tap()
catch() catchError()
switch() switchAll()
finally() finalize()
throw() throwError()
14
4. RxJS — Observables RxJS
An observable is a function that creates an observer and attaches it to the source where
values are expected from, for example, clicks, mouse events from a dom element or an
Http request, etc.
Observer is an object with callback functions, that will get called when there is
interaction to the Observable, i.e., the source has interacted for an example button click,
Http request, etc.
Create Observable
Subscribe Observable
Execute Observable
Create Observable
The observable can be created using observable constructor and also using observable
create method and by passing subscribe function as an argument to it as shown below:
testrx.js
import { Observable } from 'rxjs';
We have created an observable and added a message “My First Observable” using
subscriber.next method available inside Observable.
testrx.js
import { Observable } from 'rxjs';
15
RxJS
Subscribe Observable
You can subscribe to an observable as follows:
testrx.js
import { Observable } from 'rxjs';
When the observer is subscribed, it will start the execution of the Observable.
Execute Observable
An observable gets executed when it is subscribed. An observer is an object with three
methods that are notified,
next(): This method will send values like a number, string, object etc.
complete(): This method will not send any value and indicates the observable as
completed.
Let us create the observable with all three notifications and execute the same.
testrx.js
import { Observable } from 'rxjs';
var observer = new Observable(function subscribe(subscriber) {
try{
16
RxJS
In the above code, we have added, next, complete and error method.
try{
subscriber.next("My First Observable");
subscriber.next("Testing Observable");
subscriber.complete();
} catch(e){
subscriber.error(e);
}
To execute next, complete and error, we have to call the subscribe method as shown
below:
17
5. RxJS ― Operators RxJS
Operators are an important part of RxJS. An operator is a pure function that takes in
observable as input and the output is also an observable.
In above example we have created a observable using of() method that takes in values
1, 2 and 3. Now on this observable you can perform different operation using any numbers
of operators using pipe() method as shown above. The execution of operators will go on
sequentially on the observable given.
Output
18
RxJS
30
In above example, we have used filter operator that, filters the even numbers and, next
we have used reduce() operator that will add the even values and give the result when
subscribed.
Creation
Mathematical
Join
Transformation
Filtering
Utility
Conditional
Multicasting
Error handling
Creation Operators
Following are the operators we are going to discuss in Creation operator category:
Operator Description
19
RxJS
Mathematical Operators
The following are the operators we are going to discuss in the Mathematical operator
category:
Operator Description
20
RxJS
Join Operators
The following are the operators we are going to discuss in the Join operator category.
Operator Description
Transformation Operators
The following are the operators we are going to discuss in the Transformation operator
category.
Operator Description
21
RxJS
Filtering Operators
The following are the operators we are going to discuss in the filtering operator category.
22
RxJS
Operator Description
Utility Operators
The following are the operators we are going to discuss in the utility operator category.
Operator Description
Conditional Operators
The following are the operators we are going to discuss in the conditional operator
category.
Operator Description
24
RxJS
Multicasting Operators
The following are the operators we are going to discuss in the multicasting operator
category.
Operator Description
25
RxJS
Operators Description
ajax
This operator will make an ajax request for the given url. To work with ajax we need to
import it first as follows:
Example
import { map, retry } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';
Output
26
RxJS
from
This operator will create an observable from an array, an array-like object, a promise, an
iterable object, or an observable-like object.
Syntax
Parameters
Example
Output
27
RxJS
fromEvent
This operator will give output as an observable that is to be used on elements that emit
events for example buttons, clicks, etc.
Syntax
Parameters
eventName: eventName you want to capture for example click, mouseover, etc.
Return value
It returns an observable.
Example
Output
28
RxJS
fromEventPattern
This operator will create an observable from the input function that is used to register
event handlers.
Syntax
Parameters
Return value
Returns an observable when the event happens, for example, click, mouseover, etc.
Example
function addBtnClickHandler(handler) {
document.getElementById("btnclick").addEventListener('click', handler);
}
Output
29
RxJS
interval
This operator will create an Observable every time for the time given.
Syntax
interval(time): Observable
Parameters
Return value
It returns an observable, that will give a sequential number for the timeinterval given.
Example
Output
of
This operator will take in the arguments passed and convert them to observable.
Syntax
of(input: array[]):Observable
Parameters
30
RxJS
Return value
Example
Output
range
This operator will create an Observable that will give you a sequence of numbers based
on the range provided.
Syntax
Parameters
start: The first value will be from start and will emit sequentially until the count given.
Return value
It returns an Observable that will give you a sequence of numbers based on the range
provided.
Example
31
RxJS
Output
throwError
This operator will create an observable that will notify an error.
Syntax
Parameters
error: The argument the operator takes in is the error that you need to notify.
Return value
Example
Output
32
RxJS
timer
This operator will create an observable that will emit the value after the timeout and the
value will keep increasing after each call.
Syntax
Parameters
Return value
An observable that will emit the value after the timeout and the value will keep increasing
after each call.
Example
Output
33
RxJS
iif
This operator will decide which Observable will be subscribed.
Syntax
iif(condition: Function):Observable
Parameters
condition: The condition is a function if its return true the observable will be subscribed.
Return value
Example
of("Even Case"),
of("Odd Case")
34
RxJS
);
task1.subscribe(value => console.log(value));
iff() operator acts like a ternary operator and mostly used for if-else condition cases.
Output
Odd Case
count
count() takes in an Observable with values and converts it into an Observable that will
give a single value. The count function takes in predicate function as an optional
argument. The function is of type boolean and will add value to the output only if the value
is truthy.
Syntax
Parameters
predicate_func : (optional) Function that will filter the values to be counted from the source
observable and return a boolean value.
Return value
The return value is an observable that has the count of the given numbers.
Let us see some examples of count without predicate and with function.
Example 1
Output
The count is 6
35
RxJS
Example 2
The function we have used in the count is to give the count only of even numbers.
Output
The count is 4
max
max() method will take in an observable with all values and return an observable with the
max value. It takes in a compare function as an argument, which is optional.
Syntax
Parameters
comparer_func: (optional). A function that will filter the values to be considered for max
value from the source observable. If not provided the default function is considered.
Return value
The return value is an observable that will have the max value.
Example 1
36
RxJS
Example 2
We are using arrays and the values inside the array are compared using the function given
in max function, the max value from the array is returned.
Output
min
min() method will take in an observable with all values and return an observable with
the min value. It takes in a compare function as an argument, which is optional.
Syntax
Parameters
comparer_func: (optional). A function that will filter the values to be considered for min
value from the source observable.If not provided the default function is considered.
Return value
The return value is an observable that will have the min value.
Example 1
37
RxJS
Output
Example 2
Output
Reduce
In reduce operator, accumulator function is used on the input observable, and the
accumulator function will return the accumulated value in the form of an observable, with
an optional seed value passed to the accumulator function.
The reduce() function will take in 2 arguments, one accumulator function, and second is
the seed value.
Syntax
Parameters
accumulator_func: a function that is called on the source values from the observables.
Return Value
We will see some examples to see how the reduce operator works.
Example 1
let items = [
{item1: "A", price: 1000.00},
38
RxJS
Output
concat
This operator will sequentially emit the Observable given as input and proceed to the next
one.
Syntax
Parameters
Return value
An observable is returned with a single value merged from the values of the source
observable.
Example
Output
39
RxJS
forkJoin
This operator will take in an array or dict object as an input and will wait for the observable
to complete and return the last values emitted from the given observable.
Syntax
Parameters
value: The value is the input which can be an array or dict object.
Return value
An observable is returned with last values emitted from the given observable.
Example
Output
[6,36]
40
RxJS
merge
This operator will take in the input observable and will emit all the values from the
observable and emit one single output observable.
Syntax
merge(observable:array[]): Observable
Parameters
Return value
Example
Output
race
It will give back an observable that will be a mirror copy of the first source observable.
41
RxJS
Syntax
Parameters
Return value
It will return an observable that will be a mirror copy of the first source observable.
Example
Output
buffer
The buffer operates on an observable and takes in argument as an observable. It will start
buffering the values emitted on its original observable in an array and will emit the same
when the observable taken as argument emits. Once the observable taken as arguments
emites the buffer is resets and starts buffering again on original till the input observable
emits and the same scenario repeats.
Syntax
Parameters
input_observable: an observable that will make the buffer emit values. For example,
button click.
Return Value
42
RxJS
An observable will be returned, that will have an array of buffered values. We will work on
an example to understand the working of the buffer() operator.
In the example below, we are going to use a button click as an observable input to buffer.
The interval of 1s will be as original observable on which buffer is called. The buffer will
collect the clicks passed in the time interval given.
Example
Output
bufferCount
In the case of buffercount operator, it will collect the values from the observable on which
it is called and emit the same when the buffer size given to buffercount matches. It takes
2 arguments buffersize and the second one is startBufferEvery i.e. it will count the new
values from startBufferEvery if given or else from the beginning of the source observable.
Syntax
Parameters
43
RxJS
Return value
Example 1
In the above example, the bufferSize is 4. So, after a count of 4 clicks the array of click
events is collected in an array and displayed. Since we have not given the startBufferEvery
the values will be counted from the start.
Output
Example 2
44
RxJS
In this example, we have added startBufferEvery, so after every 2 clicks, it will display a
buffer count of 4 click events.
Output
bufferTime
This is similar to bufferCount, so here, it will collect the values from the observable on
which it is called and emit the bufferTimeSpan is done. It takes in 1 argument, i.e.,
bufferTimeSpan.
Syntax
Parameters
Return Value
Example
In the example the time used is 4seconds, So, bufferTime() operator will accumulate the
clicks and after every 4 seconds will display them as shown below.
Output
45
RxJS
bufferToggle
In the case of bufferToggle it takes 2 arguments, openings and closingSelector. The
opening arguments are a subscribable or a promise to start the buffer and the second
argument closingSelector is again subscribable or promise an indicator to close the buffer
and emit the values collected.
Syntax
Parameters
closingSelector: A function that will take the values from openings observable and return
Subscribable or promise.
Return Value
Example
In the example above the buffer will start after 2s and end when we 1s interval if the value
received is even otherwise it will empty the buffer values and emit empty values.
Output
46
RxJS
bufferWhen
This operator will give the values in the array form, it takes in one argument as a function
that will decide when to close, emit and reset the buffer.
Syntax
Parameters
Return Value
Example
For bufferWhen we have given a function that executes at an interval of 5 seconds. So,
after every 5 seconds, it will output all the clicks recorded and will get reset and start
again.
Output
47
RxJS
expand
The expand operator takes in a function as an argument which is applied on the source
observable recursively and also on the output observable. The final value is an observable.
Syntax
expand(recursive_func:observable): Observable
Parameters
recursive_func: A function is applied to all the values coming from the source and returns
an Observable.
Return Value
Example
Output
48
RxJS
groupBy
In groupBy operator, the output is grouped based on a specific condition and these group
items are emitted as GroupedObservable.
Syntax
Parameters
keySelector_func: A function that gives the key for each item from the source observable.
Return Value
Example
const data = [
{groupId: "QA", value: 1},
{groupId: "Development", value: 3},
49
RxJS
from(data).pipe(
groupBy(item => item.groupId)
)
.subscribe(x => console.log(x));
If you see the output, it is an observable wherein the items are grouped. The data we have
given has 2 groups QA and Development. The output shows the grouping of the same as
shown below:
Output
map
In the case of map operator, a project function is applied on each value on the source
Observable and the same output is emitted as an Observable.
Syntax
Parameters
project_func: It takes in project_func as the argument which is applied to all the values of
source observable.
Return Value
Example
50
RxJS
Output
mapTo
A constant value is given as output along with the Observable every time the source
Observable emits a value.
Syntax
Parameters
value: It takes in the value as an argument and this value will be a map to the source
value given.
Return Value
Example
Output
51
RxJS
mergeMap
In the case of mergeMap operator a project function is applied on each source value and
the output of it is merged with the output Observable.
Syntax
Parameters
project_func: It takes in project_func as the argument which is applied to all the values of
source observable.
Return value
It returns an Observable that has values based on the project_func applied on each value
of source observable.
Example
Output
52
RxJS
switchMap
In the case of switchMap operator, a project function is applied on each source value and
the output of it is merged with the output Observable, and the value given is the most
recent projected Observable.
Syntax
Parameters
project_func: It takes in project_func as the argument which is applied to all the values
emitted from source observable and returns an Observable.
Return Value
The return value is an Observable, that has values based on the project_func applied on
each value of source observable.
Example
Output
window
It takes an argument windowboundaries which is an observable and gives back a nested
observable whenever the given windowboundaries emits
Syntax
Parameters
53
RxJS
Return value
Example
Output
debounce
A value emitted from the source Observable after a while and the emission is determined
by another input given as Observable or promise.
Syntax
Parameters
Return value
It returns an observable wherein the emission of the source observable is delayed based
on the durationSelector.
Example
54
RxJS
Output
debounceTime
It will emit value from the source observable only after the time span is complete.
Syntax
Parameters
Return value
It returns an observable wherein the emission of the source observable is delayed based
on the dueTime.
Example
55
RxJS
debounceTime(2000)
);
case1.subscribe(x => console.log(x));
Same as debounce() operator , with the only difference, is that you can pass the delay
time to this operator directly.
Output
distinct
This operator will give all the values from the source observable that are distinct when
compared with the previous value.
Syntax
distinct()
Return value
Example
let all_nums = of(1, 6, 15, 1, 10, 6, 40, 10, 58, 20, 40);
let final_val = all_nums.pipe(distinct());
final_val.subscribe(x => console.log("The Distinct values are "+x));
Output
56
RxJS
elementAt
This operator will give a single value from the source observable based upon the index
given.
Syntax
Parameters
index: The argument passed is the index of type number, starting from 0. The value from
the source observable for this index will be given back.
Return value
Example
We have used elementAt(4), so the 5th click will be emitted as the index starts from 0.
Output
57
RxJS
filter
This operator will filter the values from source Observable based on the predicate function
given.
Syntax
Parameter
predicate_func: The predicate_func, will return a boolean value, and the output will get
filtered if the function returns a truthy value.
Return value
Example
Output
58
RxJS
first
This operator will give the first value emitted by the source Observable
Syntax
first()
Return value
Example
The first() operator gives the first value from the list given.
Output
last
This operator will give the last value emitted by the source Observable.
Syntax
last()
Return value
Example
The last() gives the last value from the list provided.
Output
ignoreElements
This operator will ignore all the values from the source Observable and only execute calls
to complete or error callback functions.
Syntax
ignoreElements()
Return value
It returns an observable that will call complete or error based on the source observable.
Example
ignoreElements() operator will directly execute the complete method if success and error
if failure and ignore everything else.
60
RxJS
Output
sample
This operator will give the most recent value from the source Observable, and the output
will depend upon the argument passed to it emits.
Syntax
Parameters
notifier: The argument notifier is an Observable which will decide the output to be picked.
Return value
Example
The sample() operator is given interval(4000) so the click event will get emitted when the
interval of 4seconds is done.
Output
61
RxJS
skip
This operator will give back an observable that will skip the first occurrence of count items
taken as input.
Syntax
Parameters
count: The argument count is the number of times that the items will be skipped from the
source observable.
Return value
It will return an observable that skips values based on the count given.
Example
We have given count as 2 to skip() operator so the first two clicks are ignored and the
third click event is emitted.
Output
throttle
This operator will output as well as ignore values from the source observable for the time
period determined by the input function taken as an argument and the same process will
be repeated.
Syntax
62
RxJS
Parameters
Return value
It will return an observable that will throttle the values emitted from the source observable.
Example
When you click on the button the first click event will be emitted, the subsequent clicks
will be delayed for the time given to throttle() operator.
Output
tap
This operator will have the output the same as the source observable and can be used to
log the values to the user from the observable. The main value, error if any or is the task
is complete.
Syntax
Parameters
63
RxJS
complete: (optional) complete() method will get called when the task is complete.
Return value
Example
Output
delay
This operator delays the values emitted from the source Observable based on the timeout
given.
Syntax
64
RxJS
Parameters
timeout: It will be in milliseconds or a Date which will delay the emission of the values
from the source observable.
Return value
An observable will be returned that will use the timeout or date given to delay the source
observable.
Example
The button click event will be delayed by 2seconds using delay() operator as shown below.
Output
delayWhen
This operator delays the values emitted from the source Observable based on the timeout
from another observable taken as input.
Syntax
Parameters
Return value
65
RxJS
An observable will be returned that will use timeoutSelector_func output to delay the
source observable.
Example
We have used an observable for delayWhen(), and when that observable emits the click
event is emitted.
Output
observeOn
This operator based on the input scheduler will reemit the notifications from the source
Observable.
Syntax
observeOn(scheduler): Observable
Parameters
scheduler: The scheduler is used as an input that will help to re-emit the notifications from
the source observable.
Return value
It will return an observable same as source observable, but with scheduler param.
Example
66
RxJS
Output
subscribeOn
This operator helps to asynchronous subscribes to the source Observable based on the
scheduler taken as input.
Syntax
subscribeOn(scheduler): Observable
Parameters
67
RxJS
scheduler: The scheduler is used as an input that will help to re-emit the notifications from
the source observable.
Return value
It will return an observable same as source observable, but with scheduler param.
Example
Output
timeInterval
This operator will return an object which contains current value and the time elapsed
between the current and previous value that is calculated using scheduler input taken.
Syntax
timeInterval(scheduler): Observable
Parameters
scheduler: (optional) The scheduler input is used to calculate the time elapsed between
the current and previous value from source Observable.
Return value
It will return an observable that will have source values and also the time interval.
68
RxJS
Example
Output
timestamp
Returns the timestamp along with the value emitted from source Observable which tells
about the time when the value was emitted.
Syntax
timestamp(): Observable
Return value
Returns the timestamp along with the value emitted from source Observable which tells
about the time when the value was emitted.
Example
69
RxJS
timestamp()
);
final_val.subscribe(x => console.log(x));
Output
timeout
This operator will throw an error if the source Observable does not emit a value after the
given timeout.
Syntax
Parameters
timeout: The input to it is the timeout which can be of type number or Date within which
the value from the source Observable must be emitted.
Return value
Example
e => console.log(e),
() => console.log("Task complete")
);
The observable interval will go on and the timeout is given as new Date ("October 01,
2019 10:40:00"), so at that time the timeout will occur and it will throw an error as shown
below.
Output
toArray
Accumulates all the source value from the Observable and outputs them as an array when
the source completes.
Syntax
toArray():Observable
Return value
Returns an observable that outputs the values from the source observable as an array
when the source completes.
Example
Output
[2, 3, 4, 5, 6]
defaultIfEmpty
This operator will return a default value if the source observable is empty.
Syntax
Parameters
defaultValue: The argument defaultValue can be given some value or if not given it is
null by default.
Return value
It will return an observable with a default value if the source observable is empty.
Example
Output
Empty! No values
every
It will return an Observable based on the input function satisfies the condition on each of
the value on source Observable.
72
RxJS
Syntax
Parameters
predicate_func: The input given to this operator is a predicate_func that will take in the
source item and checks if it satisfies the condition given.
Return value
It returns an Observable based on the input function satisfies the condition on each of the
value on source Observable.
Example
Output
false
find
This will return the observable when the first value of the source Observable satisfies the
condition for the predicate function taken as input.
Syntax
Parameters
predicate_func: The input given to this operator is a predicate_func that will take in the
source item and checks if it satisfies the condition given.
Return value
It will return the observable when the first value of the source Observable satisfies the
condition for the predicate function taken as input.
Example
Output
24
findIndex
This operator will give you the index of the first value from source Observable which
happens to satisfy the condition inside the predicate function.
Syntax
Parameters
predicate_func: The predicate_function will be deciding the first index to be picked when
the condition satisfies.
Return value
It will return an observable with the first value from source Observable which happens to
satisfy the condition inside the predicate function
Example
Output
74
RxJS
isEmpty
This operator will give the output as true if the input observable goes for complete callback
without emitting any values and false if the input observable emits any values.
Syntax
isEmpty(): Observable
Return value
It will return an observable with a boolean value as true if the source observable is empty
otherwise false.
Example
Since the source observable is empty, the output given by observable is true.
Output
true
multicast
A multicast operator shares the single subscription created with other subscribers. The
params that multicast takes in is a subject or a factory method that returns a
ConnectableObservable that has to connect() method. To subscribe connect() method has
to be called.
Syntax
Params
Before we get into the working of a multicast() operator, let us first understand how the
multicast() operator is helpful.
Example
} catch (e) {
subscriber.error(e);
}
});
const subscribe_one = observable.subscribe(val => console.log("Value from Sub1
= "+val));
const subscribe_two = observable.subscribe(val => console.log("Value from Sub2
= "+val));
Output
If you see the output the values for Sub1 and Sub2 are different. This is because when
the subscriber gets called the observable restarts and gives the fresh value available. But
we need the subscribers getting called to have the same value.
Example
If you now see the same value is shared between the subscribers that are called.
Output
publish
publish() operator gives back ConnectableObservable and needs to use connect() method
to subscribe to the observables.
Syntax
publish()
Example
77
RxJS
observable1.connect();
Output
publishBehavior
publishBehaviour make use of BehaviourSubject, and returns ConnectableObservable. The
connect() method has to be used to subscribe to the observable created.
Syntax
publishBehaviour(defaultvalue)
Example
Output
78
RxJS
The default value will be displayed first and later the value from the observable.
publishLast
publishBehaviour make use of AsyncSubject, and returns ConnectableObservable. The
connect() method has to be used to subscribe to the observable created.
Example
Output
79
RxJS
publishReplay
publishReplay make use of behaviour subject, wherein, it can buffer the values and replay
the same to the new subscribers and returns ConnectableObservable. The connect()
method has to be used to subscribe to the observable created.
Syntax
Example
Output
80
RxJS
share
It is an alias for multicast() operator with the only difference is that you don't have to
called connect () method manually to start the subscription.
Syntax
share()
Example
Output
81
RxJS
catchError
This operator takes care of catching errors on the source Observable by returning a new
Observable or an error.
Syntax
Parameters
selector_func: The selector func takes in 2 arguments, error function and caught which is
an Observable.
Return value
Example
return el;
}),
catchError(err => {
console.error(err.message);
82
RxJS
Output
retry
This operator will take care of retrying back on the source Observable if there is error and
the retry will be done based on the input count given.
Syntax
Parameters
Return value
Example
83
RxJS
final_val.subscribe(
x => console.log(x),
err => console.error(err),
() => console.log("Task Complete")
);
In the example, we are making a call to a url using ajax. The url:
http://localhost:8081/getData is giving a 404 so the retry() operator tries to make a call
to url again for 4 times. The output is shown below:
Output
84
6. RxJS — Working with Subscription RxJS
When the observable is created, to execute the observable we need to subscribe to it.
count() operator
Here, is a simple example of how to subscribe to an observable.
Example 1
import { of } from 'rxjs';
import { count } from 'rxjs/operators';
Output
The count is 6
The subscription has one method called unsubscribe(). A call to unsubscribe() method will
remove all the resources used for that observable i.e. the observable will get canceled.
Here, is a working example of using unsubscribe() method.
Example 2
import { of } from 'rxjs';
import { count } from 'rxjs/operators';
The subscription is stored in the variable test. We have used test.unsubscribe() the
observable.
Output
The count is 6
85
7.RxJS ― Working with Subjects RxJS
A subject is an observable that can multicast i.e. talk to many observers. Consider a button
with an event listener, the function attached to the event using add listener is called every
time the user clicks on the button similar functionality goes for subject too.
Create a subject
What is the Difference between Observable and Subject?
Behaviour Subject
Replay Subject
AsyncSubject
Create a subject
To work with subject, we need to import Subject as shown below:
next(v)
error(e)
complete()
Subscribe to a Subject
You can create multiple subscription on the subject as shown below:
subject_test.subscribe({
next: (v) => console.log(`From Subject : ${v}`)
});
subject_test.subscribe({
86
RxJS
The subscription is registered to the subject object just like addlistener we discussed
earlier.
subject_test.next("A");
The data will be passed to all the subscription added on the subject.
Example
Here, is a working example of the subject:
subject_test.subscribe({
next: (v) => console.log(`From Subject : ${v}`)
});
subject_test.subscribe({
next: (v) => console.log(`From Subject: ${v}`)
});
subject_test.next("A");
subject_test.next("B");
The subject_test object is created by calling a new Subject(). The subject_test object has
reference to next(), error() and complete() methods. The output of the above example is
shown below:
Output
We can use complete() method to stop the subject execution as shown below.
87
RxJS
Example
import { Subject } from 'rxjs';
subject_test.subscribe({
next: (v) => console.log(`From Subject : ${v}`)
});
subject_test.subscribe({
next: (v) => console.log(`From Subject: ${v}`)
});
subject_test.next("A");
subject_test.complete();
subject_test.next("B");
Once we call complete the next method called later is not invoked.
Output
Example
Below is a working example:
subject_test.subscribe({
error: (e) => console.log(`From Subject : ${e}`)
});
88
RxJS
subject_test.subscribe({
error: (e) => console.log(`From Subject : ${e}`)
});
subject_test.error(new Error("There is an error"));
Output
Example
Here is a working example of same:
Output
89
RxJS
Now, here the problem is, we want the same data to be shared, but not, at the cost of 2
Http calls. We want to make one Http call and share the data between subscribers.
This will be possible using Subjects. It is an observable that can multicast i.e. talk to many
observers. It can share the value between subscribers.
Example
Here is a working example using Subjects:
subject_test.subscribe({
next: (v) => console.log(v)
});
subject_test.subscribe({
Output
90
RxJS
Now you can see only one Http call and the same data is shared between the subscribers
called.
Behaviour Subject
Behaviour subject will give you the latest value when called.
Example
Here is a working example to use Behaviour Subject:
behavior_subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
behavior_subject.next("Hello");
91
RxJS
behavior_subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
behavior_subject.next("Last call to Behaviour Subject");
Output
Replay Subject
A replaysubject is similar to behaviour subject, wherein, it can buffer the values and replay
the same to the new subscribers.
Example
Here is a working example of replay subject:
replay_subject.subscribe({
next: (v) => console.log(`Testing Replay Subject A: ${v}`)
});
replay_subject.next(1);
replay_subject.next(2);
replay_subject.next(3);
replay_subject.subscribe({
next: (v) => console.log(`Testing Replay Subject B: ${v}`)
});
92
RxJS
replay_subject.next(5);
The buffer value used is 2 on the replay subject. So the last two values will be buffered
and used for the new subscribers called.
Output
AsyncSubject
In the case of AsyncSubject the last value called is passed to the subscriber and it will be
done only after complete() method is called.
Example
Here is a working example of the same:
async_subject.subscribe({
next: (v) => console.log(`Testing Async Subject A: ${v}`)
});
async_subject.next(1);
async_subject.next(2);
async_subject.complete();
async_subject.subscribe({
next: (v) => console.log(`Testing Async Subject B: ${v}`)
});
93
RxJS
Here, before complete is called the last value passed to the subject is 2 and the same it
given to the subscribers.
Output
94
8. RxJS ― Working with Scheduler RxJS
A scheduler controls the execution of when the subscription has to start and notified.
Here is a working example, wherein, we will use the scheduler that will decide the
execution.
Example
import { Observable, asyncScheduler } from 'rxjs';
import { observeOn } from 'rxjs/operators';
console.log("Observable Created");
observable.subscribe(
x => console.log(x),
(e)=>console.log(e),
()=>console.log("Observable is complete")
);
console.log('Observable Subscribed');
95
RxJS
Output
96
9. RxJS ― Working with RxJS and Angular RxJS
In this chapter, we will see how to use RxJs with Angular. We will not get into the
installation process for Angular here, to know about Angular Installation refer this link:
https://www.tutorialspoint.com/angular7/angular7_environment_setup.htm
We will directly work on an example, where will use Ajax from RxJS to load data.
Example
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = '';
data;
constructor() {
this.data = "";
this.title = "Using RxJs with Angular";
let a = this.getData();
}
getData() {
const response =
ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response));
response.subscribe(res => {
console.log(res);
this.data = res;
97
RxJS
});
}
}
app.component.html
<div>
<h3>{{title}}</h3>
<ul *ngFor="let i of data">
<li>{{i.id}}: {{i.name}}</li>
</ul>
</div>
<router-outlet></router-outlet>
We have used ajax from RxJS that will load data from this url:
https://jsonplaceholder.typicode.com/users.
98
10. RxJS — Working with RxJS and ReactJS RxJS
In this chapter, we will see how to use RxJs with ReactJS. We will not get into the
installation process for Reactjs here, to know about ReactJS Installation refer this link:
https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.html
Example
We will directly work on an example below, where will use Ajax from RxJS to load data.
index.js
))}
99
RxJS
</ul>
</div>
);
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>ReactJS Demo</title>
</head>
<body>
<div id = "root"></div>
</body>
</html>
We have used ajax from RxJS that will load data from this Url :
https://jsonplaceholder.typicode.com/users.
100