1 Universitatea Babeș -Bolyai Cluj-Napoca Facultatea de Matematică și Informatică Specializare: Masterat Software Engineering Reactive Web… [605245]

1 Universitatea Babeș -Bolyai Cluj-Napoca
Facultatea de Matematică și Informatică
Specializare: Masterat Software Engineering

Reactive Web Applications

Lucrare de dizertație

Conducător științific Absolventă

Prof. Dr. Bazil Pârv Roxana -Elisabeta Oneț

Anul 2018

2

3 Table of Contents
INTRODUCTION ………………………….. ………………………….. ………………………….. ………………………….. ….. 5
1.1 WEB APPLICATIONS ………………………….. ………………………….. ………………………….. …………………….. 7
1.1.1 A SHORT HISTORY OF WEB APPLICATIONS ………………………….. ………………………….. ……………………. 7
1.1.2 INTRODUC TION ………………………….. ………………………….. ………………………….. ……………………….. 9
1.1.3 HOW WE DEFINE WEB APPLICATIONS ? ………………………….. ………………………….. ………………………… 9
1.1.4 HOW LONG HAVE WEB APPLICATIONS BEEN AROUND ? ………………………….. ………………………….. … 10
1.1.5 WHAT ARE THE BENEFITS OF USING WEB APPLICATIONS ? ………………………….. ………………………….. 10
1.1.6 STRUCTURE ………………………….. ………………………….. ………………………….. ………………………….. 11
1.1.7 HOW A WEB APPLICATION WORKS ? ………………………….. ………………………….. ………………………….. 11
1.1.8 BUSINESS USE ………………………….. ………………………….. ………………………….. ……………………….. 13
1.1.9 WHAT IS THE FUTURE OF WEB APPLICATIONS ………………………….. ………………………….. ……………… 14
1.2 USER INTERFACE DESIGN ………………………….. ………………………….. ………………………….. ……………. 14
1.2.1 USER EXPERIENCE MODELS ………………………….. ………………………….. ………………………….. ………. 15
1.2.1.1 Models of Creating User Experience ………………………….. ………………………….. ………………… 15
1.2.1.2 UX research model ………………………….. ………………………….. ………………………….. …………. 18
1.3 REACTIVE USER INTERFACE ………………………….. ………………………….. ………………………….. ………….. 19
1.3.1 INTRODUCTION ………………………….. ………………………….. ………………………….. ………………………. 19
1.3.2 HOW WE DEFINE REACTIVE UI ? ………………………….. ………………………….. ………………………….. …… 20
1.3.3 REACTIVE PROGRAMMING ………………………….. ………………………….. ………………………….. …………. 21
1.3.3. 1 What is Reactive Programming? ………………………….. ………………………….. …………………….. 21
1.3.3.2 Why should I consider adopting Reactive Programming? ………………………….. ………………… 23
1.3.3.3 Reactive Programming != Reactive System ………………………….. ………………………….. ………. 24
1.3.3.4 Reactive eXtension ………………………….. ………………………….. ………………………….. …………. 24
1.3.3.4.1 Why use Observables ………………………….. ………………………….. ………………………….. ……. 25
2. ANGULAR ………………………….. ………………………….. ………………………….. ………………………….. …… 26
2.1 ANGULAR BASICS ………………………….. ………………………….. ………………………….. ………………….. 26
2.2 ANGULAR JS VS ANGULAR ………………………….. ………………………….. ………………………….. …………… 27
2.3 HOW ANGULAR WORKS ? ………………………….. ………………………….. ………………………….. ……………. 27
2.4 THE IMPORTANCE OF STATIC TYPING IN ANGULAR ………………………….. ………………………….. ………….. 28
3. CLUJUNITED – BUILDING A REACTIVE WEB APPLICATION TO SERVE THE CLUJ COMMUNITY ……………………. 28
3.1 Specifications ………………………….. ………………………….. ………………………….. ……………………… 28
3.2 Building ClujUnited Web Application ………………………….. ………………………….. ……………………. 29
4. CONCLUSION ………………………….. ………………………….. ………………………….. ………………………….. … 36
BIBLIOGRAPHY ………………………….. ………………………….. ………………………….. ………………………….. …. 37

4 Acronyms

W3C/WWW – World Wide Web
UI – User Interface
API – Application Programming Interface
JSP – Java Server Pages
ASP – Active Server Pages
XML – Extensible Markup Language
JSON – JavaScript Object Notation
MVC – Model -View -Controller
HTML – HyperText Markup Language
CGI – Common Gateway Interface
PHP – Hypertext Preprocessor
IBM – International Business Machines
SaaS – Software as a service
AJAX – Asynchronous JavaScript and XML
CSS – Cascading Style Sheets
DOM – Document Object Model
CERN – European Organization for Nuclear Research (Conseil Européen pour la Recherche
nucléaire)
SLAC – Stanford Linear Accelerator Center
SQL – Structured Query Language
UX – User eXperience
CPU – Central Processing Unit
I/O – Input/Output
RX – Reactive eXtension
IOS – iPhone OS
JS – JavaScript
REST – REpresentational State Transfer
CLI – Command Line Interface

5 Introduction

Cluj Napoca city is constantly expanding and neighbourhoods are getting more
crowded. This growth become harder to manage and the Town Hall might become more
distant in the relationship with the citizens. A lot more projects are on the backlog and
many priorities to define. In this context we believe the citizens should get work closely
with the Town Hall to ensure an organic growth of the city. Each citizen has a
reposonsability for the good of his fellow citizens and multiple communities are formed
around the town. Over the years we have seens multiple efforts from the Town Hall to
work closely with it's citizen and we salute this approach. A few applications are detailed
below.

In Cluj we already have an application, called MyCluj , for citizens to report
problems to Towh Hall. They respond to the problem reported and reply to users. You
also have nice statistics of how many opened reports are there and how many have
been solved and you can also filter by time. This application is pretty usefull, yet has
some limitations. It doesn't allow citizens to come up with project proposals, like building
a park or a kindergardern. Also, once the issue is reported the citizens don't have any
visibility over it's status. Was it seen? Who is fixing it? Whare is the deadline? What are
the milestones?

There was also another application where citizens could propose projects for 6
domains and then vote them. These projects have a buget, description and number of
votes. However, the same limitation. Once the voting session was completed, we have
no overview of the winning projects, no idea when it will begin or complete and what are
the milestones.

In order to achive a solid and healthy collaboration between the citizens and it's
leaders , we believe transparancy and good comun ication are key points. That's how we
decided to create ClujUnited application where citizens can propose Projects. Each
project will describe the problem it tries to solve and have a solution for it. This way we
encourage and engage citizens in coming up with solutions for improving the life in
community. Projects are voted and implemented and there is clear transparency of
project execution details. More about application functionalities can be found in chapter
3.

For the past 6 years I've been working on customer facing projects and I've
grown interested in providing a smooth user experience. This project seemed the
perfect fit for me to learn more about this latest trend and explore it's benefits.

In the following chapters we will start our journey with the appearance of web
applications and how they evolved over the years. We will dive also into Reactive
programming concepts to understand better what we try to achieve. In chapter 2 we will
look at today's technologies like Angular and Reactive eXtension that allow us to build
Reactive Web Applications. In chapter 3 we will look at how we did this for Cluj United.

6

7 Building reactive web applications

1.1 Web Applications

1.1.1 A short history of web applications

The World Wide Web ("WWW" or simply the "Web") is a global information
medium which users can read and write via computers connected to the Internet. The
term is often mistakenly used as a synonym for the Internet itself, but the Web is a
service that operates over the Internet, just as e-mail also does. The history of the
Internet dates back significantly further than that of the World Wide Web. Web is the
global information system.

Berners -Lee wrote a proposal on March 13, 1989 for "a large hypertext database
with typed links". Although the proposal attracted little interest, Berners -Lee was
encouraged by his boss, Mike Sendall, to begin implementing his system on a newly
acquired NeXT workstation. He considered several names, includin g Information Mesh,
The Information Mine or Mine of Information, but settled on World Wide Web.

By Christmas 1990, Berners -Lee had built all the tools necessary for a working
Web: The HyperText Transfer Protocol (HTTP) 0.9, the HyperText Markup Language
(HTML), the first Web browser (named WorldWideWeb, which was also a Web editor),
the first HTTP server software (later known as CERN httpd), the first web server
(http://info.cern.ch), and the first Web pages that described the project itself.

In keepin g with its birth at CERN and the first page opened, early adopters of the
World Wide Web were primarily university -based scientific departments or physics
laboratories such as Fermilab and SLAC. By January 1993 there were fifty Web servers
across the world . In April 1993 CERN made the World Wide Web available on a royalty –
free basis. By October 1993 there were over five hundred servers online. Two of the
earliest webcomics started on the World Wide Web in 1993: Doctor Fun and NetBoy

By the end of 1994, the total number of websites was still minute compared to
present figures, but quite several notable websites were already active, many of which
are the precursors or inspiring examples of today's most popular services.

By 1996 it became obvious to most publicly traded companies that a public Web
presence was no longer optional. Though at first people saw mainly the possibilities of
free publishing and instant worldwide information, increasing familiarity with two-way
communication over the "Web" led to the possibility of direct Web-based commerce (e-
commerce) and instantaneous group communications worldwide. More dotcoms,
displaying products on hypertext webpages, were added into the Web.

8 Low interest rates in 1998 –99 facilitated an increase in start-up companies.
Although several these new entrepreneurs had realistic plans and administrative ability,
most of them lacked these characteristics but were able to sell their ideas to investors
because of the novelty of the dot-com concept.

Historically, the dot-com boom can be seen as similar to a number of other
technology -inspired booms of the past including railroads in the 1840s, automobiles in
the early 20th century, radio in the 1920s, television in the 1940s, transistor electronics
in the 1950s, computer time-sharing in the 1960s, and home computers and
biotechnology in the 1980s.

In 2001 the bubble burst, and many dot-com startups went out of business after
burning through their ventur e capital and failing to become profitable. Many others,
however, did survive and thrive in the early 21st century. Many companies which began
as online retailers blossomed and became highly profitable. More conventional retailers
found online merchandisin g to be a profitable additional source of revenue. While some
online entertainment and news outlets failed when their seed capital ran out, others
persisted and eventually became economically self-sufficient.

In the aftermath of the dot-com bubble, telecommunications companies had a
great deal of overcapacity as many Internet business clients went bust. That, plus
ongoing investment in local cell infrastructure kept connectivity charges low, helped to
make high-speed Internet connectivity more affordable . During this time, a handful of
companies found success developing business models that helped make the World
Wide Web a more compelling experience. These include airline booking sites, Google's
search engine and its profitable approach to keyword -based advertising, as well as
eBay's auction site and Amazon.com's online department store.

This new era also begot social networking websites, such as MySpace and
Facebook, which gained acceptance rapidly and became a central part of youth culture.
The 2010s also saw the emergence of various controversial trends, such as the
expansion of cybercrime, of the manosphere and of internet censorship.

As the Web became easier to query, it attained a greater ease of use overall and
gained a sense of organization which ushered in a period of rapid popularization. Many
new sites such as Wikipedia and its Wikimedia Foundation sister projects were based
on the concept of user-edited content. In 2005, three former PayPal employees created
a video viewing website called YouTube, which quickly became popular and introduced
a new concept of user-submitted content in major events.

The popularity of YouTube, Facebook, etc., combined with the increasing
availability and affordability of high-speed connections has made video content far more
common on all kinds of websites. Many video -content hosting and creation sites provide
an easy means for their videos to be embedded on third party websites without payment
or permission.

9 Continued extension of the Web has focused on connec ting devices to the
Internet, coined Intelligent Device Management. As Internet connectivity becomes
ubiquitous, manufacturers have started to leverage the expanded computing power of
their devices to enhance their usability and capability. Through Interne t connectivity,
manufacturers are now able to interact with the devices they have sold and shipped to
their customers, and customers are able to interact with the manufacturer (and other
providers) to access new content. [10]

1.1.2 Introduc tion

In earlier computing models like client –server, the processing load for the
application was shared between code on the server and code installed on each client
locally. In other words, an application had its own pre-compiled client program which
served as its user interface and had to be separately installed on each user's personal
computer. An upgrade to the server -side code of the application would typically also
require an upgrade to the client -side code installed on each user workstation, adding to
the support cost and decreasing productivity. In addition, both the client and server
components of the application were usually tightly bound to a particular computer
architecture and operating system and porting them to others was often prohibitively
expensive for all but the largest applications. (Nowadays, native apps for mobile devices
are also hobbled by some or all of the foregoing issues.)

In contrast, web applications use web documents written in a standard format
such as HTML and JavaScript, which are suppo rted by a variety of web browsers. Web
applications can be considered as a specific variant of client –server software where the
client software is downloaded to the client machine when visiting the relevant web page,
using standard procedures such as HTTP. Client web software updates may happen
each time the web page is visited. During the session, the web browser interprets and
displays the pages, and acts as the universal client for any web application. [1]

1.1.3 How we define web applications?

A web application or web app is a client –server computer program which the
client (including the user interface and client -side logic) runs in a web browser. [1] The
"client" is used in client -server environment to refer to the program the person uses to
run the application. A client -server environment is one in which multiple computers
share information such as entering information into a database. The "client" is the
application used to enter the information, and the 'server' is the application used to store
the information. [3] The web browsers are the software application that allow users to
retrieve data and interact with content on pages in a website.

From a technical point of view, the web is a programmable environment that
allows for mass customization through the immediate deployment of a wide and diverse
range of applications to millions of users globally. Two important components of a
modern website are the flexibility of web browsers and the flexibility of web applications,
both available to everyone and diversified at no cost.

10
Web application is a software system based on the World Wide Web Consortium
(W3C) technologies and standards that provide specific web resources such as content
and services through an interface called web browser. A web application consists of an
application that is accessed by users on a network, such as the Internet or intranet. The
term can also mean a computer software application that is encoded in a browser –
supported programming language (such as JavaScript and comb ined with a
programming language like HTML) that relies on a common web browser for make the
application executable.

Web applications are popular due to the ubiquity of web browsers, and due to the
convenience of using a web browser as a client, sometime s called a client that does not
have much resources. The ability to update and maintain web applications without
distributing and installing software on thousands of potential customers is the main
reason for their popularity, as inherent support for platform compatibility. Common web
applications include emails, online vouchers, online auctions, wikis and many other
features. [2]

The easy way to keep in mind what a web application can do, is to think of it as
any computer program that performs a specific function by using a web browser as its
client. Web application s can be as simple as a message board or a contact form on a
website or as complex as a word processor or a multi -player mobile gaming app that
you download to your phone.[3]

1.1.4 How Long Have Web Applications Been Around?

Web applications have been around since before the World Wide Web gained
mainstream popularity. For example, Larry Wall developed Perl, a popular server -side
scripting language, in 1987. That was seven years before the internet really started
gaining popularity outside of academic and technology circles.

The first mainstream web applications were relatively simple, but the late 90s
saw a push toward more complex web applications. Nowadays, millions of Americans
use web application to file their income taxes online, perform online banking tasks, stay
in touch with friends and loved ones and so much more. [3]

1.1.5 What Are the Benefits of Using Web Applications?

A web application relieves the developer of the responsib ility of building a client
for a specific type of computer or a specific operating system, so anyone can use the
application along as they have internet access. Since the client runs in a web browser,
the user could be using an IBM-compatible or a Mac. They can be running Windows XP
or Windows Vista. They can even be using Internet Explorer or Firefox, though some
applications require a specific Web browser.

11 Web applications commonly use a combination of server -side script (ASP, PHP,
etc) and client -side script (HTML, Javascript, etc.) to develop the application. The client –
side script deals with the presentation of the information while the server -side script
deals with all the hard stuff like storing and retrieving the information. [3]

1.1.6 Structure

Applications are usually divided into logical parts, called levels, and each level is
assigned a role. Traditional applications consist of a single layer that is in the client
area, but web applications by definition are based on an n-level approach. Although we
have several possible variants, we most often encounter the 3 level approach. The most
common form and order of the three levels is the following: presentation, application
logic and storage. The web browser is the first level (the presentation), the system using
dynamic web technologies (such as JSP / Java, ASP, ASP.NET, CGI, ColdFusion,
PHP, Perl, Python, Ruby on Rails or Struts2) middle (application logic), and a database
is the third level (storage). The web browser sends middle -level requests that perform
queries and updates to the database so that the user interface is generated.

For more complex applications, the solution offered by the three levels may not
be good enough, and it may be better to use a n-level approach where the greatest
benefit is that you can divide business logic at the application level, in a finer form of
granulation. Another benefit could be adding an integration level that separates the data
level from the rest of the levels by providing an easy to use and accessible interface.
For example, client data can be accessed by calling a "list_clients ()" function instead of
a SQL query directly on the client table in the database. This allows you to modify the
database without changing the other levels.

There are some who see a web application as a two-level architecture. This may
be a "smart" client who does the whole thing and interrogates a "bad" server, or a "bad"
client based on a "smart" server. The client will handle the presentation level, the server
will have the database (storage level) and the logic of the application will be processed
by one or both of them. While this increases the scalability of applications and
separates the database interface, it still does not allow true leveling specialization,
which causes this model to be outdated for most applications. [1]

1.1.7 How a web application works?

Web applications are usually coded in browser -supported language such as
JavaScript and HTML as these languages rely on the browser to render the program
executable . Some of the applications are dynamic, requiring server -side processing.
Others are completely static with no processing required at the server.

The web application requires a web server to manage requests from the client,
an application server to perform the tasks requested, and, sometimes, a database to
store the information. Application server technology ranges from ASP.NET, ASP and
ColdFusion, to PHP and JSP. [4]

12
The picture below describes what happens in a web application flow. First, the
user triggers a request to the web server over the Internet, either through a web
browser or the application’s user interface. Then the web server forwards this request to
the appropriate web application server which performs the requested task – such as
querying the database or processing the data – then generates the results of the
requested data. Next, the web application server sends results to the web server with
the requested information or processed data and the web server responds back to the
client with the requested information that then appears on the user’s display
Fig. 1.1 Typical web application flow [4]

The figure below shows how the initial request is triggered by the user through
the browser over the Internet to the web application server. The web application
accesses the databases servers to perform the requested task updating and retrieving
the information lying within the database. The web application then presents the
information to the user through the browser. [5]

13

Fig. 1.2 Typical web application flow [5]

In more technical terms, web applications query the content server (essentially a
content repository database) and dynamically generate web documents to serve to the
client (people surfing the website). The documents are generated in a standard format
to allow support by all browsers (e.g., HTML or XHTML). JavaScript is one form of
client -side script that permits dynamic elements on each page (e.g., an image changes
once the user hovers over it with a mouse). The web browse r is key – it interprets and
runs all scripts etc. while displaying the requested pages and content. Wikipedia
brilliantly terms the web browser as the “universal client for any web application.”[5]

1.1.8 Business use

An emerging strategy for software application companies is to provide web
access to previously distributed software as local applications. Depending on the type of
application, it may be necessary to develop a completely different browser interface, or
simply to adapt an existing applicatio n to use a different presentation technology. These
programs allow the user to pay a monthly or yearly fee for using a software application

14 without having to install it on a hard drive. A company that uses this strategy is known
as an Application Service Provider (ASP), and ASP is currently receiving a lot of
attention in the software industry.

Security breaches about these types of applications are a major concern, as they
can involve both business information and customer personal information. Protectin g
these assets is an important part of any web application and there are some key
operational areas that need to be included in the development process. These include
authentication, authorization, asset handling, input, and operating and audit processes.
Building security in applications from the beginning can be more effective and less
disturbing in the long run.

In the cloud computing model, web applications are service software (SaaS).
There are business applications offered as SaaS for businesses with fixed or usage
fees. Other web applications are provided free of charge, often generating revenue from
advertisements presented in the web application interface. [1]

1.1.9 What is the future of Web Applications

The new push for web applications is crossing the line into those applications
that do not normally need a server to store the information. Your word processor, for
example, stores documents on your computer, and doesn’t need a server.
If you have seen the new Gmail or Yahoo mail clients, you have seen how sophisticated
web applications have become in the past few years. Much of that sophistication is
because of AJAX, which is a programming model for creating more responsive web
applications. Google Apps and Microsoft Office Live are examples of the newest
generation of web applications.

As the number of businesses embracing the benefits of doing business over the
web increases, so will the use of web applications and other related technologies.
Moreover, since the increasing adoption of intrane ts and extranets, web applications
become greatly entrenched in any organization’s communication infrastructures, further
broadening their scope and possibility of technological complexity and prowess. [5]

1.2 User Interface Design

This section explores how new systems should approach the User Interface (UI).
It has now become increasingly important and challenging to create the best user

15 interfaces. An ineffective interface can turn a good system into one that is difficult to use
and discourages users from coming back. A good user interface is especially important
for meeting hedonic, aesthetic and innovation needs.

From a software designer point of view, a system must provide the desired
functionality, while the user is looking for the most enjoyable experience when using the
system. This dichotomy is articulated by Nielsen distinguishing between two
approaches to IU design:

1. Task oriented paradigm
2. Experience -oriented Paradigm

Nielsen seems to prefer the UI-designed task approach when it states, "There
are basically two basic design approaches: the art one, ideal to express yourself and
engineering, ideal to solve a customer's problem. This book is firmly focused on
engineering. While I admit that there is need for art, fun, and quali ty time on the web, I
think the main objective of most web projects should be ensuring ease of customer
satisfaction “ [6]

1.2.1 User Experience Models

Experience is a twisted and difficult to define concept, so before it can be used
effectively in designing the system, it must be placed on a theoretical ground. The
theory of experience generation is still under development and the following
subchapters present some theoretical models that can be used.
1.2.1.1 Models of Creating User Experience

Many attempts have been made to define the concept of experience. "Lapland
Center of Expertise for the Experience Industry" defines the experience as "a multi –
sensory, positive and vast emotional experience that can lead to personal change of a
person" [7]. A more detailed explanation of this definition is given by the patterns of
experience creation in Figures 1.3 and 1.4.

The user experience model presented in Fig. 1.3 shows that experience is a
continuous phenomenon. It flows like an uninterrupted flow of experience that persists
in our conscious mind as well as in our unconscious, or subconscious, when we sleep.
The so-called peak experiences are of significant strength and have the potential to
make a lasting difference for that person. Everyday experiences vary slightly, while
subconscious experiences, especially during sleep, are in the subconscious mind;
however, even these can have a significant effect depending on their significance.

16

Fig. 1.3 The user experience model [7]

Furthermore, we can share experience in internal (thinking) and external
(physical) experiences and they are interrelated. Fig. 1.4 presents the model of user
experience types and provides a classification of different experiences of different
forces internally and externally .

17
Fig. 1.4 Model of user experience types [7]

While the user experience model (Fig. 1.3) and the user experience types model
(Fig. 1.4) clarify some aspects of the user experience, these does not show how user
experience is related to the UI design process. The user experience research model
presented in the next subchapter shows how we can do this. [7]

18 1.2.1.2 UX research model

In reality, tasks are linked by user experience (User Experience, UX). We need a
model that connects users' actions to UX. The User Experience Research Model
(UExR) presented in Fig. 1.5 makes this connection on five levels [8].

Fig. 1.5 The user experience research model

Given that UX is a concept that is difficult to define, we link it to more concrete
concepts taken from cognitive and behavioral sciences as presented in the five-level
model in the figure above. In this model we place UX (which is the most ephemeral
conce pt) on level 5, and then connect it with the most physics concept (systems and
components) placed at level 1.

From the cognitive science literature, we can confirm that emotions play a central
role in everything UX [9], therefore, emotions are placed on level 4. Feelings and
thoughts are responsible for producing emotional reactions, so they are placed at level
3. Here feelings refer to emotional feelings, such as happy or sad , and not to physical
sensations, such as hot or cold. [8]

Thoughts appear in the brain and are sometimes accompanied by verbal and / or
visual responses in mind. In addition, thoughts give rise to feelings, for example,
positive thoughts create positive feelings, such as happiness, and negative thoughts
can create negative feeling s such as jealousy, anger, etc. These feelings exist in the
mind and connect thoughts to behavior.

Because the mind connects thoughts with behavior and actions, the latter are
placed on level 2 in the UXeR model. Behaviors are action templates. Physical

19 components are placed at level 1, which includes the system with all its components,
such as user interface entities and hardware devices used to perform actions and tasks.

Thus, the UXeR model provides a step-by-step bridge that can cover the gap
betwee n the two UI paradigms: task-oriented and experience -oriented. However, more
formal relationships need to be developed to provide a systematic process of creating
user-friendly interfaces that meet the user's need to perform the task while providing a
high intensity experience.

1.3 Reactive User Interface

1.3.1 Introduction

Reactive User Interfaces are a declarative way of expressing your app’s visual
representation of DATA. Data is the keyword here. As UI Engineers, our responsibility is
to take the truth of the server and present that to our users in a natural way. [11]

Actually, the best UI is invisible. It facilitates users to get things done through it in
a natural way, with minimal conscious thought on the UI itself.

Reactive or Declarative user interfaces separate UI State (the DATA) from the
underlying layout of the user’s visual experience (THE DOM). This allows us to write
components by declaring how the rendering should translate our data into visual
elements on the DOM. With these trigger s in place, we can continue to update state to
get DOM adjustments automatically. [11]

A human -to-computer user interface is said to be "reactive" if it has the following
characteristics:

• The user is immediately aware of the effect of each "gesture". Gestures can be
keystrokes, mouse clicks, menu selections, or more esoteric inputs.
• The user is always aware of the state of his/her data. Did I just save those
changes? Did I just overwrite my backup by mistake? No data is hidden. In a
figure -drawing program, the user can tell whether a line segment is composed of
smaller segments.
• The user always knows how to get help. Help may be context -sensitive or modal,
but it is substantial. A program with a built-in help browser is not reactive if its
content is just a collection of screen shots or menu item labels with no real
explanation of what they do.

Reactivity was a major goal in the early user interface research at MIT and Xerox
PARC. A computer program which was not reactive would not be considered user
friendly no matter how elaborate its presentation.

20
Early word -processing programs whose on-screen representations look nothing
like their printer output could be reactive. The common example was WordStar on
CP/M. On-screen, it looked like a markup language in a character cell display, but it had
deep built-in help which was always available from an on-screen menu bar, and the
effect of each keystroke was obvious. [12]

1.3.2 How we define ReactiveUI ?

Most modern programming today is basically imperative, meaning it models the
traditional fetch -execute cycle of a CPU. Perform an instruction, fetch the next one.
Perform that one, and so on. For decades, programmers have had to mould their brains
to fit the paradigm of the CPU. It's been like this since the early 1980s.

When we rely on hoping that the behavior that emerges from a program is
correct, and that reliance is based on nothing more than a programmer's correctness,
then we can easily find ourselves in a sticky situation. We can try and mitigate the costs
of imperative programming with things like unit tests or integration tests, but why
mitigate the costs when there's a better way?

Long ago, when computer programming first came to be, machines had to be
programmed quite manually. If the technician entered the correct sequence of machine
codes in the correct order, then the resulting program behavior would satisfy the
business requirements. Instead of telling a computer how to do its job, which error –
prone and relies too heavily on the infallibility of the programmer, why don't we just tell it
what its job is and let it figure the rest out?

ReactiveUI is inspired by the paradigm of Functional Reactive Programming,
which allows you to model user input as a function that changes over time. This is super
cool because it allows you to abstract mutable state away from your user interfaces and
express the idea around a feature in one readable place whilst improving application
testability. Reactive programming can look scary and complex at first glance, but the
best way to describe reactive programming is to think of a spreadsheet:

• Three cells, A, B, and C.
• C is defined as the sum of A and B.
• Whenever A or B changes, C reacts to update itself.

21

Fig. 1.6 Reactive programming model

That's reactive programming: changes propagate throughout a system
automatically. [13]

Another example is a hardware description language such as Verilog, where
reactive programming enables changes to be modeled as they propagate through
circuits.

1.3. 3 Reactive Programming
1.3.3.1 What is Reactive Programming?

In computing, reactive programming is a declarative programming paradigm
concerned with data streams and the propagation of change. With this paradigm it is
possible to express static (e.g. arrays) or dynamic (e.g. event emitters) data streams
with ease, and also communicate that an inferred dependency within the associated
execution model exists, which facilitates the automatic propagation of the changed data
flow.

Reactive programming has been proposed as a way to simplify the creation of
interactive user interfaces, (near) real time system animation. For example, in a model –
view–controller (MVC) architecture, reactive programming can facilitate changes in an
underlying model that are reflec ted automatically in an associated view.[14]

Reactive programming is programming with asynchronous data streams. In a
way, this isn't anything new. Event buses or your typical click events are really an
asynchronous event stream, on which you can observe and do some side effects.
Reactive is that idea on steroids. You are able to create data streams of anything, not
just from click and hover events. Streams are cheap and ubiquitous, anything can be a
stream: variables, user inputs, properties, caches, data structures, etc. For example,
imagine your Twitter feed would be a data stream in the same fashion that click events
are. You can listen to that stream and react accordingly.

On top of that, you are given an amazing toolbox of functions to combine, create
and filter any of those streams. That's where the "functional" magic kicks in. A stream
can be used as an input to another one. Even multiple streams can be used as inputs to
another stream. You can merge two streams. You can filter a stream to get another one

22 that has only those events you are interested in. You can map data values from one
stream to another new one. [15]

Fig. 1.7 Click event stream

A stream is a sequence of ongoing events ordered in time. It can emit three
different things: a value (of some type), an error, or a "completed" signal. Consider that
the "completed" takes place, for instance, when the current window or view containing
that button is closed.

We capture these emitted events only asynchronously, by defining a function that
will execute when a value is emitted, another function when an error is emitted, and
another function when 'completed' is emitted. Sometimes these last two can be omitted
and you can just focus on defining the function for values . The "listening" to the stream
is called subscribing. The functions we are defining are observers. The stream is the
subject (or "observable") being observed. This is precisely the Observer Design Pattern.

To show the real power of Reactive, let's just say that you want to have a stream
of "double click" events. To make it even more interesting, let's say we want the new
stream to consider triple clicks as double clicks, or in general, multiple clicks (two or
more). Take a deep breath and imagine how you would do that in a traditional
imperative and stateful fashion. I bet it sounds fairly nasty and involves some variables
to keep state and some fiddling with time intervals.

23

Fig. 1.7 Multiple click event stream

In the figure from above, the grey boxes are functions transforming one stream
into another. First we accumulate clicks in lists, whenever 250 milliseconds of "event
silence" has happened (that's what buffer(stream.throttle(250ms)) does, in a nutshell.).
The result is a stream of lists, from which we apply map() to map each list to an integer
matching the length of that list. Finally, we ignore 1 integers using the filter(x >= 2)
function. That's it: 3 operations to produce our intended stream. We can then subscribe
("listen") to it to react accordingly how we wish.[15]

1.3.3.2 Why should I consider adopting Reactive Programming?

Reactive Programming raises the level of abstraction of your code so you can
focus on the interdependence of events that define the business logic, rather than
having to constantly fiddle with a large amount of implementation details. Code in
Reactive Programming will likely be more concise.

The benefit is more evident in modern webapps and mobile apps that are highly
interactive with a multitude of UI events related to data events. 10 years ago, interaction
with web pages was basically about submitting a long form to the backend and

24 performing simple rendering to the frontend. Apps have evolved to be more real-time:
modifyi ng a single form field can automatically trigger a save to the backend, "likes" to
some content can be reflected in real time to other connected users, and so forth.

Apps nowadays have an abundancy of real-time events of every kind that enable
a highly interactive experience to the user. We need tools for properly dealing with that,
and Reactive Programming is an answer. [15]

1.3.3.3 Reactive Programming != Reactive System

Probably the most confusing part. Using reactive programming does not build a
reactive system. Reactive systems, as defined in the reactive manifesto, are an
architectural style to build responsive distributed systems. Reactive Systems could be
seen as distributed systems done right. A reactive system is characterized by four
propert ies:

• Responsive: a reactive system needs to handle requests in a reasonable time (I let
you define reasonable).
• Resilient: a reactive system must stay responsive in the face of failures (crash,
timeout, 500 errors …), so it must be designed for failures and deal with them
appropriately.
• Elastic: a reactive system must stay responsive under various loads. Consequently,
it must scale up and down, and be able to handle the load with minimal resources.
• Message driven: components from a reactive system interacts using asynchronous
message passing.

Despite the simplicity of these fundamental principles of reactive systems,
building one of them is tricky. Typically, each node needs to embrace an asynchronous
non-blocking development model, a task-based concurrenc y model and uses non-
blocking I/O. If you don’t think about these points first, it’s quickly going to be a spaghetti
plate.

Reactive Programming and Reactive eXtension provides a development model
to tame the asynchronous beast. By using it wisely, your code is going to stay readable,
and understandable. However, using reactive programming does not transform your
system into a Reactive System. Reactive Systems are the next level.[16]
1.3.3.4 Reactive eXtension

Reactive eXtension (RX) is an implementatio n of the reactive programming
principles to “compose asynchronous and event -based programs by using observable
sequence”. With RX, your code creates and subscribes to data streams named
Observables. While Reactive Programming is about the concepts, RX provides you an

25 amazing toolbox. By combining the observer and iterator patterns and functional idioms,
RX gives you superpowers. You have an arsenal of functions to combine, merge, filter,
transform and create the data streams. [16]

It extends the observer pattern to support sequences of data and/or events and
adds operators that allow you to compose sequences together declaratively while
abstracting away concerns about things like low-level threading, synchronization,
thread -safety, concurrent data structur es, and non-blocking I/O.

Observables fill the gap by being the ideal way to access asynchronous
sequences of multiple items.

Fig. 1.8 Synchronous vs Asynchronous methods

It is sometimes called “functional reactive programming” but this is a misnomer.
ReactiveX may be functional, and it may be reactive, but “functional reactive
programming” is a different animal. One main point of difference is that functional
reactive programming operates on values that change continuously over time, while
ReactiveX operates on discrete values that are emitted over time.

ReactiveX provides a collection of operators with which you can filter, select,
transform, combine, and compose Observables. This allows for efficient execution and
composition.

You can think of the Observable class as a “push” equivalent to Iterable, which is
a “pull.” With an Iterable, the consumer pulls values from the producer and the thread
blocks until those values arrive. By contrast, with an Observable the producer pushes
values to the consumer whenever values are available. This approach is more flexible,
because values can arrive synchronously or asynchronously.

1.3.3.4.1 Why use Observables

The ReactiveX Observable model allows you to treat streams of asynchronous
events with the same sort of simple, composable operations that you use for collections
of data items like arrays. It frees you from tangled webs of callbacks, and thereby
makes your code more readable and less prone to bugs.

26 • Observables are composable : Techniques like Java Futures are straightforward to
use for a single level of asynchronous execution but they start to add non-trivial
complexity when they’re nested. It is difficult to use Futures to optimally compose
conditional asynchronous execution flows (or impossible, since latencies of each
request vary at runtime). ReactiveX Observables, on the other hand, are intended
for composing flows and sequences of asynchronous data.

• Observables are flexible: ReactiveX Observables support not just the emission of
single scalar values (as Futures do), but also of sequences of values or even infinite
streams. Observable is a single abstraction that can be used for any of these use
cases. An Observable has all of the flexibility and elegance associated with its
mirror-image cousin the Iterable.

• Observables are less opinionated: ReactiveX is not biased toward some particular
source of concurrency or asynchronicity. Observables can be implemented using
thread -pools, event loops, non-blocking I/O, actors (such as from Akka), or whatever
implementation suits your needs, your style, or your expertise. Client code treats all
of its interactions with Observables as asynchronous, whether your underlying
implementation is blocking or non-blocking and however you choose to implement it.
[17]

2. Angular

2.1 Angular Basics

Angular is a frontend framework for building robust, cross -platform, client -side
applications. Is a platform build by Google for developing client side applications. Not
only can angular applications target web browsers for mobile and desktop devices. You
can also develop native apps for IOS and Android devices using native script.

If you are wondering why should you choose Angular, the reasons are very
straightforward. First, Angular is modular, and being modular you`re in control of every
piece of GUID you include in your application. When your application is bundled and
ready to be sent off to the browser, it will ultimately be in it`s simplest form, reducing the
time it takes to run the applicati on. In previous versions of Angular, the full Angular
framework was included with every application

27 Secondly, Angular it’s built on static language. Is the first framework to leverage
a statically typed version of JavaScript, typescript. Typescript is a type super set of
JavaScript that lets developers move quickly by keeping them in their Editor and
focused on their code. With static typing, you spend less time reading documentation
and more time building you application.

Next, it`s backed by Google and has a large community of developers. Google
has hundreds of internal applications built on Angular. The internal teams that rely on
the platform provide valuable feedback. Also, the Angular team is very involved in the
community. Angular is an open sourc e project with many contributors outside of Google.

And the most important reason, is that Angular is a platform built by and for the
community.

2.2 Angular JS vs Angular

There is an important distinction between Angular JS and Angular . Angular JS
refer to Angular version 1 and the JS has been dropped from version 2 onwards. The
removal of the JS was to show a clean break in the evolution between Angular as a
framework to become a new modern platform. Angular can be used in many different
scenarios now, not just web applications.

Angular offers a modern approach to build client side web applications. The
Angular development experience, is much different than any other front end framework.
By taking advantage of modern syntax and Typescript, Angular has a solid platform for
you to build your next application. Typescript helps developers avoid mistakes by
helping with code completion, and display warnings before developers open their
application.

2.3 How Angular works ?

Angular applications can be made up of a collection of modules. Each application
needs to have at least one Root module, which is where the application starts. When
you define your application you will need to decide on the Services, Component and
third Party Modules you need to include in your application.

Services can be internal or part of 3rd Party Modules. Services are a way to
perform actions that occur behind the scenes. Maybe it`s a long running calculation, or
it`s a web request of the data from the server.

Components are the heart of your application. These combine some templates,
styles, and some basic logic. They can be large enough to incorporate the entire user
interface, or be as small as a single button.

NgModule is like a container for your application. Ng is the name space angular
adopted, so developers can easily identify parts of the angular platform that is your

28 application. Angular depends on Node.js and NPM for module loading and package
management. Webpack has become the standard way for packaging Angular
applications. Webpack is an open source module loader, that has a lot of extensibility
through plugins and loaders.

2.4 The importance of static typing in Angular

Angular is the first major front-end framework who incorporates TypeScript.
While you may enjoy the flexibility of a dynamically -typed language such as JavaScript,
you are likely to have experienced moments where third-party libraries didn’t worked as
documented and maybe that’s because you passed in the wrong values into a method
call. This is precisely why Angular is built on TypeScript. The documentation is right
there at your fingertips when you`re developing, keeping you in the editor

Typescript is a type superset of JavaScript and it has all the same features and
syntax of JavaScript so that you don`t need to learn something new, but it includes
static typing for added safety. In addition, TypeScript allows you to write n ECMAScript
2015 syntax and have it transpired to all the versions of the language for greater
browser support.

Typescript language service is interpreting our code at design time, not when our
application runs. Typescript is baked into every Angular application, and provided you
are using an editor that supports TypeScript, you can reap the benefits of intelligent
warnings an error detection. [18]

3. ClujUnited – building a Reactive Web Application to serve the Cluj
community
3.1 Specifications

In order to achive a solid and healthy collaboration between the citizens and it's
leaders we believe transparancy and good comunication are key points. The model we
propose is based on the following concepts :

• Citizen : A person living in the city or commuting to the city and is comitted to
improving the life quality in his community.
• Town Hall : representatives from the Town Hall
• Project: Citizens and Town Hall can propose projects.
• Executor: company that is executing the project
In order to encourage users to come up with solutions the building block is a
Project. A project has a name, a motivation and a proposed solution. Specialists will

29 then come up with a project estimate or even Executants from the Application can come
up with estimation.

Citizens can express their desire for a project to become reality. The project
contains also other relevant information like numbers of beneficiaries, cost/citizen,
money available for it, total cost, needed money from private funding. At this point
citizens or companies can start a fundraise campaing to complete the project.

Once a project has all the money needed and is approved, the Town Hall will
update the information about the Executant of the project, start date, end date,
milestones and current progress. Citizen can thus have a clear overview of what's going
on, what's the state of the projects he is watching.

We believe all this will create a stonger relationship and promote the civic
camaradery among Cluj Napoca's inhabitants.

3.2 Building ClujUnited Web Application

Angular has a component -based architecture. A component is a TypeScript class
with an HTML template and an optional set of CSS styles that control a part of the
screen. Components are the most important concept in Angular 6. An Angular 6
application is basically a tree of components with a root component (the famous
AppComponent). The root componen t is the one contained in the bootstrap array in the
main NgModule module app.module.ts.

One important aspect of components is re-usability. A component can be re-used
throughout the application and even in other applications. Common and repeatable
code that performs a certain task can be encapsulated into a re-usable component that
can be called whenever we need the functionality it provides. Each bootstrapped
component is the base of its own tree of components.

An Angular application is made of several components forming a tree structure
with parent and child components. A component is an independent block of a big
system (web application) that communicates with the other building blocks
(components) of the system using inputs and outputs. A comp onent has associated
view, data and behavior and may have parent and child components. Components
allow maximum re-usability, easy testing, maintenance and separation of concerns.

Let's now see this practically. We head over to our Angular application project
folder and open the src/app/components/project -list folder where we will find the
following files for our custom component:

• project -list.component.css: the CSS file for the component
• project -list.component.html: the HTML view for the component

30 • proje ct-list.component.spec.ts: the unit tests or spec file for the component
• project -list.component.ts: the component code (data and behavior)
• project -list.module.ts: the application main module

To a better understanding of the AppComponent (The Root Compone nt of
Angular Applications) let’s go to src/app/components/project -list/project -list.module.ts
file and let's understand the code behind the main/ro ot component of the application
Fig. 3.1 The root component of the application

31 We first import the Com ponent decorator from @angular/core then we use it to
decorate the TypeScript class AppComponent. The Component decorator takes an
object with many parameters such as:

• selector : specifies the tag that can be used to call this component in HTML
templates just like the standard HTML tags
• templateUrl: indicates the path of the HTML template that will be used to display this
component (you can also use the template parameter to include the template inline
as a string)
• styleUrls: specifies an array of URLs for CSS style-sheets for the component

The export keyword is used to export the component so that it can be imported
from other components and modules in the application.

Next, let's see the corresponding template for this component. We will open
src/app/ components/project -list/project -list.component.html:

Fig. 3.2 The component template

The template is a normal HTML file (almost all HTML tags are valid to be used
inside Angular templates except for some tags such as <script>, <html> and <body>
etc.) with the exception that it can contain template variables (in this case the title
variable) or expressions ({{…}}) that can be used to insert values in the DOM
dynamically. This is called interpolation or data binding. Other components can be also
used directly inside Angular templates (via the selector property) just like normal HTML.

32 The architectural pattern used is MVC (Model View Controller) : the component
class plays the role of the Controller and the HTML template plays the role of the View.

Our REST API, built by Georgian, exposes multiple endpoints, among them one
of them is /projects which is used to create or read a paginated list of accounts.
Before adding routing to our application we first needed to create the
application's components so based on the exposed REST API architecture we can
initially divide our application into several components , among them:

• ProjectListcomponent: this component displays and controls a tabular list of projects
• ProjectCreatecomponent : this componen t displays and controls a form for creating
or updating projects

In order to be able to create the components we used Angular CLI:

• ng generate component ProjectList
• ng generate component ProjectCreate

The generated output of the first command:

CREATE src/app/components/project -list/project -list.component.css (0 bytes)
CREATE src/app/components/project -list/project -list.component.html(31 bytes)
CREATE src/app/components/ project -list/project -list.component.spec.ts (664 bytes)
CREATE src/app/components/project -list/project -list.module.ts (292 bytes)
UPDATE src/app/components/app.module.ts (418 bytes)

We can observe here that the command generates all the files to define a
component and also updates src/app/app.module.ts. If we open src/app/app.module.ts
after running all commands, we can see in the figure below that all components are
automatically added to the AppModule declarations array. In case we wanted to create
components manually, we would need to make sure to include them manual ly so they
can be recognized as part of the module.

Fig. 3.3 The AppModule

33

Angular CLI provides the –routing switch (ng new crmapp –routing) that helps us
to add routing automatically. We added routing manually for the first component in order
to understand the various pieces involved in adding component routing to our Angular
application:

• added a separate module (which we called AppRoutingM odule) in a file app-
routing.module.ts, and imported the module by including it in the imports of main
AppModule,
• Added <router -outlet></router -outlet> in app.component.html (this is where the
Angular Router will insert components matching the current path),
• Added routes (each route is an object with properties such as path and component
etc.).

Fig. 3.4 The AppRoutingModule

34 The routes will contain all the routes of the application. In the figure above, we
can see the first route added. We want to redirect the visitor to the /projects path when
the home URL is visited so the first path we added was:

• { path: '', redirectTo: 'projects ', pathMat ch: 'full' } : the pathMatch specifies the
matching strategy. full means that we want to fully match the path.

Then we added:

{
path: 'accounts',
component: AccountListComponent
},

After that we open ed src/app/app.module.ts and imported the routing module and
then added it to the imports array as you can see in figure 3.3.

Finally, we opened src/ap p/app.component.html and added the navigation links
and the router outlet:
Fig. 3.5 The AppComponent

35

After we created the components and added routing and navigation, we used the
HTTPClient of Angular 6 to consume the RESTful API back -end. We started by adding
the HttpClientModule module to the imports array of the main application module as we
can see in the figure above (Fig. 3.5 The AppModule). Next we needed to create a
service that encapsulates all the code needed for interacting with the REST API. A
service is a global class that can be injected in any component. It's used to encapsulate
code that can be common between multiple components in one place instead of
repeating it throughout various components. Using Angulat CLI we run the following
command: ng g service api

Two files: src/app/services/project -api.service.ts and src/app/services/project –
api.service.spec.ts were generated. The first contains code for the service and the
second contains tests. We opened src/app/services/project -api.se rvice.ts and then we
import ed and injected the HttpClient class.

Fig. 3.6 The project -api.service

Angular 6 provides a way to register services/providers directly in the
@Injectable() decorator by using the new providedIn attribute. This attribute accepts
any module of your application or 'root' for the main app module.

36 In order to display the data we simply need to go to our project –
list.component.html and write HTML code with ng syntax that will be processed and
interpreted. Below you can see a simple example of displaying the list of projects.

Fig. 3.7 A simple example of project -list.component.html

These are the basic steps one needs to take to build a Reactive Web Application

4. Conclusion

The current technological progress is very rapid and the degree of acceptance of
the innovations is quite high. The amount of information on the Internet is enormous, the
number of services available on the internet is increasing every year, so all we have to
do is start integrating these services and filtering data to give just what is important.

With the explosion in both the amount of internet users and the technology
powering websites over the years, reactive programming was born as a way of meeting

37 these increased demands for developers. Of course, app development is just as
important now and reactive programming is a vital component in that sphere too.

Many businesses are using this way of coding now and with good reason. As we
have noted already, it builds their app or website in such a way that it offers a better
user experience. Smoother, faster results come from programming in this manner and it
makes user interaction much better. Naturally, this translates into happier customers
and more sales for your business. [19]

Bibliography

1. https://en.wikipedia.org/wiki/Web_application
2. http://calibre.co/clindexpages/webapp.htm
3. https://www.lifewire.com/what -is-a-web-application -3486637
4. https://www.maxcdn.com/one/visual -glossary/web -application/
5. http://www.ecatechnologies.com/web -applications/
6. Nielsen, J. , in Designing Web usability: The practice of simplicity, Editura New
Riders Publishing. pp. 11
7. Gelter, H. , “Towards an unders tanding of experience production”, in M. Kylänen
(Ed.), Digital media & games , Editura University of Lapland Press., pp. 28 -51
8. Sharda, N. , in Creating ambient multimedia experience on -demand, pp 41 -48
9. Mutlu, B. D. (2004). The chaotic nature of hu man experience: Insights on the subject
matter of design towards establishing a science of design. Master’s thesis, Carnegie
Mellon University, USA.
10. https://en.wikipedia.org/wiki /History_of_the_World_Wide_Web
11. https://medium.com/modern -user-interfaces/a -journey -into-reactive -user-interfaces –
101-1daea5702486
12. https://en.wikipedia.org/wiki/Reactive_user_interface
13. https://reactiveui.net/docs/
14. https://en.wikipedia.org/wiki/Reactive_programming
15. https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
16. https://dzone.com/articles/5 -things -to-know -about -reactive -programming
17. http://reactivex.io/intro.html
18. https://teamtreehouse.com/library/w hy-angular
19. https://www.darwinrecruitment.com/blog/2017/12/why -you-should -consider -reactive –
programming

Similar Posts