Angular Lazy Loading

In this blog, we will be learning about lazy loading in angular. The main concept of lazy loading is that don’t load something which you don’t need. Lazy loading is a useful technique for reducing the size of the bundle when the app loads initially which improves the app loads time thus improving the user experience. It’s also easy to have features loaded only when the user navigates to their routes for the first time.

Main steps to set up lazy loading

  1. Create a feature module.
  2. Use loadChildren in the main routing module.
  3. Create a routing module for feature module.

Create a feature module

In order to use lazy loading, we need submodules in our applications often called a feature module. Assuming that you have an Angular CLI project, let’s create a feature module using the following command.

Create lazy loading module

Note: Don’t load the feature module in your main module.

Now let’s create two components inside the lazyLoading module using the following command.

Create lazy loading component

Use loadChildren in the main routing module

Now let’s load the feature module in our main routing module (app-routing.module.ts). We need to use loadChildren() method to lazy load the feature module.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  {
    path:'lazyLoading',
    loadChildren:
      './lazy-loading/lazy-loading.module#LazyLoadingModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

 

The loadChildren() method takes the path to the module, then # followed by the module’s class name.

Create a routing module for a feature module

Now let’s configure routes in the routing module for the components under the feature module.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { OneComponent } from './one/one.component';
import { TwoComponent } from './two/two.component';

const routes: Routes = [
{ path: '', component: OneComponent },
{ path: 'two', component: TwoComponent },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

export class LazyLoadingRoutingModule { }

 

In the feature routing module include the routes with RouterModule’s forChild() method instead of the forRoot() method.

Lazy loading has been configured successfully now LazyLoadingModule will load only when the user navigates to “/lazyLoading”.

Preloading Strategy

When we run the application only the main modules are loaded all the other modules are lazy loaded. In this case, the lazily loaded modules load only when the user navigates to the feature module. Since the module is lazy loaded we have to wait for it to be loaded to overcome this we can use preload strategy.

To use preloading strategy we have to add preloadingStrategt in our app-routing.module.ts as shown below.

import { NgModule } from '@angular/core';
import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
const routes: Routes = [
 { path: '', redirectTo: 'home', pathMatch: 'full' },
 { 
  path: 'lazyLoading', 
  loadChildren:
    './lazy-loading/lazy-loading.module#LazyLoadingModule' 
 }
];
@NgModule({
  imports: [RouterModule.forRoot(routes, {
    preloadingStrategy: PreloadAllModules,
  }
)],
exports: [RouterModule]
})
export class AppRoutingModule { }

The two subclasses in preloadingStrategy are.

  • NoPreloading: Default strategy which provides no preloading.
  • PreloadAllModules: Preloads all the lazy loaded modules.

By using PreloadAllModules we can load the modules which are required on the initial load of an application. All the other lazy loaded modules are loaded asynchronously right after the initial load of the application is done.

Another strategy is to preload the modules which are required and some other module with a delay. The method to use this is to add the data object to the route config as shown below.

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { 
    path: 'lazyLoading', 
    loadChildren: './lazy-loading/lazy-loading.module#LazyLoadingModule',
    data: { preload: true, delay: false }, 
  }
];

 

Reference:

 

Angular Flex-Layout

Flex layout is a package made for angular to use CSS flexbox features. The flex layout is used to display the elements within the flexbox container to be automatically arranged based on the parent container. Flex layout is used for building a layout structure. In this blog, we will be learning how to use angular flex layout module and its features.

Installation

Install the flex layout package with npm/yarn in your angular project.

$ npm i @angular/flex-layout

And add FlexLayoutModule into your AppModule.

Flex Layout

Let’s get started with flex layout features and how to use it and their properties.

  1. fxFlex

The fxFlex should be used on the element within the flexbox container. The fxFlex is used to resize the element based on the parent container. The fxFlex supports two usage long-form and short-form.

  • Long-form 
<div fxFlex="<grow> <shrink> <basis>"></div>
  • Short-form 
 <div fxFlex="<basis>"></div>

The flex basis value can be percentages, pixels, em, vm, vh, calcs.

Example:

<div fxFlex="20"> … </div>
  1. fxLayout

The fxLayout is used to specify the direction of the elements inside the flexbox container. Shown below are the property values of fxLayout.

  • row – Default value, the elements are displayed horizontally, as a row.
  • row-reverse – Same as the row, but in reverse order.
  • column – The elements are displayed vertically, as a column.
  • column-reverse – Same as the column, but in reverse order.
  • fxLayout + wrap – Specifies that the elements will wrap if necessary.

Note: when using the wrap, must first specify the layout direction.

Example:

<div fxLayout="row"> … </div>

<div fxLayout="row wrap"> … </div>
  1. fxLayoutGap

The fxLayout is used to specify the margin gaps on elements within the flexbox container. Shown below are the default mode of fxLayout.

  • margin-right is used when the flexbox container flex direction is a row.
  • margin-bottom is used when the flexbox container flex direction is a column.

Note: The last child element will not have the margin gap only the inside gap are specified.

Example:

<div fxLayoutGap="20px"> … </div>
  1. fxLayoutAlign

The fxLayoutAlign is used to align the elements inside a flexbox container. Shown below are the property values of fxLayoutAlign.

  • strat or flex-start – Default value, the elements are positioned at the beginning of the container.
  • end or flex-end – The elements are positioned at the end of the container.
  • center – The elements are positioned at the center of the container.
  • space-around – The elements are positioned with space before, between and after the lines.
  • space-between – The elements are positioned with space between the lines.
  • space-evenly – The elements have equal space around them.

Example:

 <div fxLayoutAlign="space-between center"> … </div>
  1. fxFlexOffset

This should be used on the element within the flexbox container. This is used to specify the margin-left to the elements within the flexbox container.

Example:

<div fxFlexOffset="20px"> … </div>
  1. fxFlexOrder

This should be used on the element within the flexbox container. This is used to specify the order for the elements inside the flexbox container.

Example:

 <div fxFlexOrder="2"> … </div>
  1. fxFlexFill

The fxFlexFill is used to maximizes the height and the width of the elements inside the flexbox container.

Example:

<div fxFlexFill> … </div>
  1. fxShow and fxHide

The fxShow and fxHide is used to show/hide the element based on the value passed to it.

Example:

<div fxHide="true"> … </div>

Responsive Layouts

The responsive layouts are used to apply different layout styles for different viewport sizes and display devices.  This can be used by combining breakpoints with fxLayout features. Some of the breakpoints are xs, sm, md, lg, xl for more reference responsive layouts.

Example:

<div fxHide.xs="true"> … </div>

Reference:

Feeling stressed ?

Feeling stressed? Absolutely you would have felt or might feel it in the future. No one can say that “I am leading a stress-free life”. So, let us understand about its flavours and how to manage it.

Everyone faces stress from time to time. People respond differently to emotions and events that may be causes of stress. For example, will say Introverts and extroverts. Both may experience the same causes of stress, but the response will be in different ways.

ARE YOU A EXTROVERT OR INTROVERT?

An extrovert tends to respond with

  • Anger
  • Impulsive actions such as: 
    • Screaming
    • Throwing objects
    • Hitting

An introvert tends to respond

  • Inwardly
  • Screaming silently at himself
  • Suffering inner anxiety
  • Depression.

        “It’s not the stress that kills you, it is our reaction to it”

FIND WHICH FLAVOUR YOU BELONG TO?

Stress comes in two flavours:

  • Eustress
  • Distress

Eustress is your body’s response to positive, happy emotions and events.

Distress is your body’s response to negative, upsetting emotions and events.

 

TIPS TO MANAGE STRESS:

And here are some tips to manage stress, have a look at it :

  • Keep a positive attitude always.

  • We need to assert our feelings, opinions, or beliefs instead of becoming angry, defensive, or passive (i.e) be assertive instead of aggressive.

  • Learn to “Say No”  to requests that would create excessive stress in our life. Set your limits.

  • There are some events or situations that we cannot control and we should accept it.
  • Eat something or chew gum. Science has shown that chewing something or eating lowers the stress.
  • We should learn and practice some relaxation techniques like meditation or yoga.

  • Walk away from your computer. Make sure to shut it off 1 hour before you fall asleep.
  • Have a stress ball at your work desk. We should use it whenever stress tries to test us.

  • Spend some time for hobbies, interests, else play with kids which would definitely reduce your stress.
  • Cuddle something. Oxytocin also called cuddle hormone get released when we spend time with others.
  • We should learn to manage our time more effectively.

  • Watch some funny videos or go for a walk.

“May be we cannot live a stress-free life,

but we can try to free us from stress”

REFERENCES:

Insights on code reviews

“Anybody can write code if he learns programming. But what makes him stand out of the crowd is the quality of the code”. Yes, the way you write and construct the code defines you as developer. Before anything else, how many of us feel to read another person’s code? How do we feel looking into our own code post 6 months ? There might be some suggestions that pops in our mind like, “Oh! I would have written like this/that”, which you would have never thought during coding that piece of code. Likewise, there may be some suggestions by our peers that could improve your code, which people name it as “Code review”. People often fail to understand the purpose of code review. We have cultivated a habit of code review as nitpicking. Ofcourse, it is partly yes! But the main purpose according to me is to share the knowledge and enhance the quality. Let’s dig deeper into it.

I still remember the first time when I was given an opportunity to review a code. I didn’t have a clear checklist or flow to review a code. But I had a few vague points(do’s and don’ts) which I learnt through the experiences of my projects. I started noting it down and framed my own checklists and reviewed. After my maiden review, whenever I code, I started following my own checklists. That’s when I realized, how could these checklists make a huge impact on the quality of the code. Believe me or not, each time when you do a code review, it enlightens us in one way or another !

When do you think your code is good to go ?

Well, it depends on who reviews it. When you go to a peer, he/she will have her own criteria. When it comes to another person the criteria will vary, where one focuses on formatting while the other doesn’t. This will lead to inconsistent feedback. Instead, we must have a common checklist/criteria in your organization which are open to developers and reviewers. In Squashapps, we have a set of 10-15 criterias and developers check those before submitting for the review. This would be good approach to be followed as it saves time and this also lets developer’s know what to be focussed on while coding.

Automate your work !

When you know what your organization needs as a quality check, you can automate them. We can use few plugins like ESLint, which will alert you from writing stupid codes. If a pattern of your code is already reviewed, you could create a reviewed template on your own and use it for further development like the one given in this link: https://code.visualstudio.com/docs/editor/userdefinedsnippets .

Don’t make the code review a nightmare!

It is always better to have a small code reviews. Yes, I do understand the fact that some features may have lesser codes while some may have a week or a month’s work. In the case of a week or a month’s work the code gets piled up which may lead to more review comments. This will become a nightmare for both reviewers and developers. When it comes to bigger features, it is always better to do a frequent small releases. This will make the other developers to get the updated code and also reduce the merge conflict to an extent.

There are three points of time, where a code can be reviewed:

  1. During implementation
  2. When code is ready to merge
  3. After code is merged

During implementation:

Reviewing with your team mate or any colleague while developing a feature, will make you get ideas from a different perspective. Here is were pair programming dives in. This will not only helps you to find bugs in your flow, it also increases the bus factor. Else the code will be known only by one developer in your team and this may lead to may issues. Pair programming helps us to get different solutions to the same, where we can have options to choose the best approach.

When code is ready to merge.

In this stage the code is reviewed by a gatekeeper like a senior developer, who is assigned to approve/decline the code to push to production.

After code is merged.

We all may think, why do we review after merging? As I said earlier, reviewing is not only finding bugs in the code, it also means to share knowledge and get feedback. In this stage of reviewing, the customers/clients checks whether the code is understandable by them.

How comments play an important role in code review ?

When it comes to reviewing of a small part in a big feature, the reviewers might not know what are all you have accomplished. To make your code speak and make it self-documented, it is good to add comments like :

// This function may fail if transportMode==Train, but there are currently no 

// documented requirements or data for Trains, so there's no way to reliably test it.

function sampleFunction (transportMode) {

// Some code

}

You could also add your thought process describing why you have chosen an approach instead of other approach. So the reviewer might know, that you have thought about the other approaches too.

Submitting for a review:

It is our prime responsibility to sync up with the reviewers in a periodic time. Once you have submitted the code, there might be further feedback or declining of code. The code has to go under some process or iterations to meet the level of standards and to push to production.

Hope you guys got something from my writing to improve the code quality.

Happy coding!

Inspired from :

https://youtu.be/jXi8h44cbQA

Validations in Full Stack Development

Full Stack Development, a quite tough to explain in a couple of lines. It takes ownership of the entire application from top to bottom. If you see a person as Full Stack Developer, he must be an all-rounder to develop an application from zero to high excellence. Full Stack Development includes 2 layers of architecture :

  1. Front-End Development (aka Client-Side / Presentation Layer)
  2. Back-End Development (aka Server-Side / Business Logic Layer)

Each Layer should have a data validations. Let’s dive in deeper,

Client-Side Validations

Validation takes place on the client side(web browser). It would be more frustrating to wait for the server response and re-enter the form that has nearly 100 inputs. So it is mainly for formatting data instantly and for the quick error recovery process.
Client-side validation gives the user feedback ASAP without having to wait for the server. It is an added topping, but not necessary. This will avoid the majority of validation issues and unnecessary processing from the server to perform data validations.

Pros:

  • Faster than Server-Side Validation
  • Better user experience can be provided by responding quickly(like invalid phone number, required fields,etc..)
  • Saves network bandwidth, traffic API calls

Cons:

  • Not Secure and useless if client-side scripts are disabled(javascript disabled)

Server-Side Validations

It is all about the data validation takes place on the server-side using the server-side scripting language. If you use server-side validation, you are developing a more secure application. Because client-side validations can be bypassed easily.

Let’s take a scenario. If a user is a technical guy/ a malicious user, he can pass invalid inputs through API testing tool or he can disable the javascript in client script or some malicious attack to skip client side validations. In these cases, validation will not happen. This may lead to incorrect entries, server downtime if any serious errors, etc, So we should verify on the server as well.

There are few libraries(eg., express-validator, etc) available to validate the inputs. Better, write a few code snippets for validations before continuing your business logic like

router.post(‘/api’, async(req, res) => {

 let isValidationPassed= await validateAndHandleInputs(req);

 if(isValidationPassed){

  //continue the business logics

 }

})

Pros:

  • More Secure than Client-Side Validation
  • Validation Techniques and Logics cannot be viewed/modified by the user.

Cons

  • Comparatively slower execution

References:

  1. https://www.smashingmagazine.com/2009/07/web-form-validation-best-practices-and-tutorials/
  2. https://medium.com/@davidpetri/server-and-client-side-validation-with-javascript-html-and-hapi-js-eccc779e448a
  3. http://net-informations.com/faq/asp/validation.htm
  4. https://surajdeshpande.wordpress.com/2013/08/10/difference-between-server-side-validation-and-client-side-validation/

Dropbox exordium

Hi Readers,

The idea about this blog is to cover the basic steps which we have to do, to integrate Dropbox with our application. The readers should have a minimal understanding of access_token, webhooks.

Recently I have started to do integration for my web application. The one which I integrated first was Dropbox

The Requirements are:

Fetch the dropbox files.

Get the corresponding redirect link.

Get the shared users for a file.

To integrate Dropbox into our Application:

  1. Create a Dropbox box app in the Dropbox developers site.
  2. After creation, use the ClientId and Client Secret of the app for authentication.

How to authenticate a user ??

The auth process can be done in two ways:

1. By creating a separate login.

2. By Click on a particular redirect link.

Note: The API URL should be encoded with client ID obtained.

Example:

https://www.dropbox.com/oauth2/authorize?response_type=code&client_id=” ”redirect_uri=””’

Redirect URI  →  The endpoint to receive the auth credentials.

After successful authentication, the auth credentials can be obtained in the redirect_uri.

Ohh, Wait! We are not close to getting the files.

Use the auth code, to get the Access_token for a user. Hit the following API endpoint with the auth code. https://api.dropboxapi.com/oauth2/token

Sample code:

let options = {

               url:https://api.dropboxapi.com/oauth2/token,

               qs: {
                  
                   'code': authCode,(code obtained by authentication)

                   'grant_type': 'authorization_code',

                   'client_id': '',

                   'client_secret': '',

                   'redirect_uri': ''

               },

               method: 'POST',

               json: true

           }

           return request_promise(options);

I have used request_promise to get the results. The redirect_uri should be same as the redirect URI provided during authentication.

Things to remember:

1. Redirect URI should be the same.

2. The Dropbox Client Id and Client Secret should be entered.

Hooray! We completed the process
Heaven, the dropbox access token will never expire.

The access token can be removed by only revoking.

How to drag the files from Dropbox to our App ??

The files  can be obtained by hitting the  following API endpoint :

https://api.dropboxapi.com/2/files/list_folder

The API returns the folders and files in a one-way tree. Nested files and folders can be obtained by setting the recursive field to true in the API hit.

Webhooks hit:

The Webhook hit can be configured in the Dropbox app which we created. Specify the corresponding webhooks URL. For authentication, the App will verify the URL by hitting with a challenge parameter. The app should be responded back with the challenge parameter.

Once the authentication is done, the webhooks hits the URL whenever the user of our app drops some files in their Dropbox.

References:

The dropbox also provides an API Explorer where the developers can view the live functioning of the API Endpoints

https://dropbox.github.io/dropbox-api-v2-explorer/

To know more about Dropbox  integration visit this link: https://www.dropbox.com/developers

 

 

Materialise your Angular App

As much as I love Angular, I also recognize that there are a few things that could make your Angular App look even more stunning without much effort! So, let’s go ahead and change your life in about 5 minutes by getting productive with Material Design using Angular Material in your Angular CLI app.

So, What Exactly is Angular Material?

Angular Material Design is a design language for web and mobile apps which was developed by Google in 2014. Material Design makes it easy for developers to customize their UI while still keeping a good-looking app interface that users are comfortable with and also you’ll get a well-organized format along with the flexibility to express your brand and style. For an example of Material Design, check out Airbnb, Gmail, and Houzz. These apps make the best use of Material Design to fit its many features into the limited mobile device. Going through the official Material design documentation is quite an experience. I recommend taking a look at the docs, but I will summarize it here.

Setup the Environment for Angular

To work with Angular, you will need Node.js and Angular CLI (Command Line Interface) installed in your development environment. Proceeding further, you can use the following command to set up a new Angular project.

ng new angular-material-app

Step 1: Install Angular Material and Cdk

Head over to your terminal, navigate inside your created Angular front-end application and then run the following commands to install Angular Material 6 and Angular 6 CDK.

npm install --save @angular/material @angular/cdk

Step 2: Install Angular Animations

In order to add enable support for animations in your Angular 6 front-end application, head back to your terminal and run the following command to install the Angular animations module and import the BrowserAnimationsModule and add it to the list of imports.

npm install --save @angular/animations

Step 3: Angular Material Theme

Angular Material comes prepackaged with several pre-built theme CSS files. To configure the basic theme, open the src/styles.css file and import any one of the available themes in Material Themes.

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

Step 4: Angular Material Gesture

Some components like Slide Toggle, Slider, and Tooltip rely on a library called HammerJS to capture touch gestures. So, you will need to install HammerJS and import it into our application.

npm install --save hammerjs

Step 5: Angular Material Icons (Optional)

If you want to use the mat-icon component with the official Material Design Icons, load the icon font in your index.html. For more information on using Material Icons, check out the Material icons guide.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

And yeah, Now you are good to go!

Note:  You can create an app-material module file for importing the angular material components and export them wherever necessary! Let’s write clean code and be a Better programmer!

What Will You Build with Angular Material?

After setting up the project structure and some dependencies, you will be able to start developing apps. You could try out some examples with the built-in components that are provided in Material docs. In this blog, to know about Angular material implementation, we will be implementing it with some small examples that play a major role in any webpage! The idea of this blog is to show how cool and easy it is to use Angular Material.

Example 1: Layout

The most widely used layout is cards. The most basic card needs only an <mat-card> element with some content. However, Angular Material provides a number of preset sections that you can use inside of an <mat-card>. For now, just copy the following code into your HTML file and you could witness a card display!

<mat-card> Simple Card</mat-card>

Example 2: Navigation

Next comes the navigation part of a webpage. <mat-menu> is a floating panel containing the list of options. By itself, the <mat-menu> element does not render anything. The menu is attached to and opened via application of the matMenuTriggerFor directive as follows.

<button mat-button [matMenuTriggerFor]="menu">Menu</button>
 <mat-menu #menu="matMenu">
   <button mat-menu-item>Item 1</button>
   <button mat-menu-item>Item 2</button>
 </mat-menu>

Example 3: Progress Bar

    “Boredom, according to psychologists, is merely lack of stimulation,the unfulfilled desire for satisfying activity. So what if we use the interface to give them that stimulation?”

~ Alice Kotlyarenko

Yeah! The UI progress bar will make you enjoy the wait! Angular Material made it easy to display a progress bar with customizable modes.

<mat-progress-bar mode="indeterminate"></mat-progress-bar>

Conclusion

I hope this blog has helped you understand how to use the power of Material Design in your app for a top-notch UI. For more information about Material Design in Angular 6, check out the official docs which contain ready-to-use templates. It’s a great place to learn about Angular. Thus Angular Material components create a beautiful application without investing too much time thinking about styles. Awesome, right?

Reference:

SwitchMap in rxjs

Let’s dive deep into switchMap with an example, so it helps as to understand what is it and when to use it.

Say we need to implement functionality for traffic signal which consists of 4 roads(A, B, C, D) meeting at a junction. The signals of these roads can be controlled either manually or automatically. The signal change is asynchronous(Observable- data stream).

const roadSignals = Observable.from(['Road SignalA', 'Road SignalB', 'Road SignalC', 'Road SignalD' ]);

roadSignals.subscribe((signal)=>console.log(signal));

Output: 

Road SignalA 

Road SignalB

Road SignalC

Road SignalD

Here comes the next part. We have to allow vehicles to pass through the junction when the signal is ON. Let’s try doing this with the help of the map. (Map -transform the items emitted by an Observable by applying a function to each item. Click here to learn about map )

roadSignals.pipe(

    .map((signal) => changeSignal(signal)),

    .map((allow) => allow.allowVehiclesObservable())

    ).subscribe((vehiclesObservable) => {

        vehiclesObservable.subscribe((vehicle) => console.log(vehicle))

    });

Here the vehicles in roads refer to an observable. So the output will be an Observable inside an Observable. We have to subscribe them in order to get vehicles individually.

In our case, allowVehiclesObservable is the outer Observable and vehiclesObservable is the inner Observable. We need to subscribe the vehiclesObservable(inner Observable) in order to get the vehicles individually. This method is called as FLATTENING.(subscribe inside a subscribe).

Come on let’s do flattening to get vehicles individually.

roadSignals.pipe(

    .map((signal) => changeSignal(signal)),

    .map((allow) => allow.allowVehiclesObservable())

    ).subscribe((vehiclesObservable) => {

        vehiclesObservable.subscribe((vehicle) => console.log(vehicle))

    });

Let a1, a2,.. b1, b2,.. be the vehicles in Road A, B, ..respectively.

Output :

a1

a2

a3

b1

b2

a4

Yes! Now we get vehicles individually. Flattening works:)

Wait a sec. What’s happening. Vehicles from Road A  as well as Road B is also moving. There are chances for accidents. After a few seconds, Signal C and Signal D will go ON. What if the vehicles from all the roads are moving.

 

Oh no. We should stop this. How to do this?

Whenever flattening is used we should use a Flattening Strategy.

  1. We need to store a subscription to the current vehiclesObservable subscription.
let subscription; (declare at top);

subscription = vehiclesObservable.subscribe(vehicle => console.log(vehicle));
  1. If new vehiclesObservable comes in we need to unsubscribe from the previous subscription before we subscribe to the new observable.
if(subscription) subscription.unsubscribe();

subscription = vehiclesObservable.subscribe(vehicle => console.log(vehicle));

Let’s apply the above steps:

let subscription;

roadSignals.pipe(

    map((signal) => changeSignal(signal)),

    map((allow) => allow.allowVehiclesObservable())

).subscribe((vehiclesObservable) => {

    if(subscription){

        subscription.unsubscribe();

    }

    subscription = vehiclesObservable.subscribe((vehicle) => console.log(vehicle))

    });

Output :

a1

a2

b1

b2

b3

c1

c2

SignalA comes first. Initially, the subscription is undefined.  RoadA-vehiclesObservable is stored in the subscription(local variable) and is subscribed. Vehicles from roadA start moving. When SignalB comes in, the subscription is defined (RoadA-vehiclesObservable). The if condition becomes true. Unsubscribe the existing subscription(RoadA-vehiclesObservable) and store the new subscription(RoadB-vehiclesObservable) to get vehicles from road B.No more vehicles from Road A..! When SignalC comes in, the existing subscription (RoadB-vehiclesObservable) is unsubscribed and new RoadC-vehicleObservable is subscribed.

As soon as the outer observable changes we kill the most recent observable and switch to new observable to replace it. Thus unsubscribing from the previous observable before subscribing to the new one is called as SWITCH Strategy.

Yes, we have achieved our desired result. But now,  the problem is the code became complex with observables, two subscribes, subscription, unsubscribe and all of these.

What to do?

Here comes switchMap for our rescue. We can replace the map and inner subscription with switchMap.

roadSignals.pipe(

    map((signal) => changeSignal(signal)),

    switchMap((allow) => allow.allowVehiclesObservable())

).subscribe((vehicle) => {

console.log(vehicle)

    });

Output :

Signal A

   vehicle a1

   vehicle a2

Signal B

   vehicle b1

   vehicle b2

Signal C

   vehicle c1

   vehicle c2

The main difference between switchMap and other flattening operators is the cancellation effect. On each emission, the previous inner observable (the result of the function you supplied) is canceled and the new observable is subscribed. You can remember this by the phrase switch to a new observable.

When to use and avoid switchMap?

switchMap can be used, when a new search is made, pending results are no longer needed; And should be avoided in scenarios where every request needs to complete, think writes to a database. switchMap could cancel a request if the source emits quickly enough.

References:

The Art of Chunking!!

How to make sense of any mess? 

Chunking makes content easier to comprehend and remember. It helps to understand the relationship between content elements and information hierarchy. By grouping each piece into a large whole, you can improve the amount of information you can remember. Chunking is one way to your product to stand out from the other competitors.

For example, a chunked phone number (+61–955–345–1234) is easier to remember (and scan) than a long string of un-chunked digits (9553451234).

Why chunking is important in UX?

Chunking Content in UX: Why chunking is important in UX?

Chunking is a concept that originates from the field of cognitive psychology. UX professionals can break their text and multimedia content into smaller chunks to help users process, understand, and easily remember within a quick span.

Presenting content in chunks makes scanning easier for the user and can improve their ability to comprehend and remember it. In practice, chunking is about creating meaningful, visually distinct content units that make sense in the context of the larger whole.

 

Key info is chunked to give clarity about the company.

Simply chunking your text isn’t enough — you also need to support scanning by making it easy to quickly identify the main points of the chunks. Some of the most commonly used methods of chunking text content are:

  1. Headings and subheadings that clearly contrast with the rest of the text (bolder, larger, etc.)
  2. Highlighted keywords (bold, italic, etc.)
  3. Bulleted or numbered lists
  4. A short summary paragraph for longer sections of text, such as articles
  5. Short paragraphs, with white space to separate them
  6. Short text lines of text (around 50–75 characters)
  7. Clear visual hierarchies with related items grouped together
  8. Distinct groupings in strings of letters or numbers such as passwords, license keys, credit card or account numbers, phone numbers, and dates (for example, 14487324534 vs 1 (448) 732 4534)

 

The contents are chunked with an illustration to give clear visual hierarchy!

The Mythical Number Seven:

Magical number seven,’ made famous by cognitive psychologist George Miller. In 1956, Miller found that most people can remember about 7 chunks of information in their short-term memory. People could remember 7 individual letters, or 28 letters if they were grouped into 7 four-letter words in a meaningful way. Designers often misunderstand the concept of Mythical Number Seven.

It doesn’t mean to give the things not more than seven to the user. Even they can still find easy to use with more than seven things at the given time.

 

Chunked infographics draw attention to the passed value here.

For UX professional, the real takeaway from Miller’s is that people with short-term memory are limited. So, if you want the people to remember more information just group them into Chunks.

Source: https://www.nngroup.com/articles/chunking/

Conclusion:

Presenting content in chunks makes scanning easier for the users and can improve their ability to comprehend and remember it.

Understanding CSS: Precedence & Specificity

Have you faced a situation where you are trying to apply the CSS style to an element, but it does not apply? It seems the webpage is ignoring your code. This could be caused by conflicts in the cascade order.

Things will discuss here:

  1. Origins of Stylesheets
  2. Specificity
  3. Importance
  4. Cascade Order

Origins of stylesheets:

  1. Author stylesheet (Styles set by the web developers)
  2. User stylesheet (Custom styles set by a user – Browsers give you the option of extending the browser’s default style sheet)
  3. Browser stylesheet / User-agent style sheet (Browser defaults – if the author of a web page didn’t apply any styling, the styling details present in the default stylesheet installed within the browser is applied)

Specificity:

        An HTML element can be targeted by multiple CSS rules. If there are two or more conflicting CSS rules, the browser will apply the rule which is more specifically mentioned. Specificity will only apply when one element has multiple declarations to it. To understand in a better way, the specificity is expressed in the form (a, b, c, d). Lets see in detail,

Specificity Hierarchy (High to Low):

  • Inline style

o   ‘style’ attribute rather than a rule with a selector

o   The position ‘a’ – (a, b, c, d) – (1, 0, 0, 0)

  • ID Selectors

o   Eg. The element with id attribute, id=’example’(#example)

o   The position ‘b’ – (a, b, c, d) – (0, 1, 0, 0)

  • Class Selectors(.example), Attribute selectors([type=radio]) and pseudo-classes(:hover)

o   The position ‘c’ – (a, b, c, d) – (0, 0, 1, 0)

  • Type Selectors(h1) and pseudo-elements (::after)

o   The position ‘d’ – (a, b, c, d) – (0,0,0,1)

Example:

Selectors Specificity
*{ } 0,0,0,0
li{ } 0,0,0,1
li:first-line { }   0,0,0,2
ul li{ }   0,0,0,2
ul ol+li{ } 0,0,0,3
h1 + *[rel=up]{ } 0,0,1,1
ul ol li.red  { } 0,0,1,3
li.red.level  { } 0,0,2,1
#exampleId{ } 0,1,0,0
style=”” 1,0,0,0

No Specificity:

  1. The universal selector (*,+, -,>, ~) has no specificity value.
  2. The pseudo-class :not() adds no specificity. The negation ‘ pseudo-class: not’ is not considered a pseudo-class in the specificity calculation. It counts as normal selectors

Origin Hierarchy:

Below is the priority order from highest to lowest for normal styles when there is equal specificity for the declarations. If it was an important style (! important), it is just the reverse.

  1. Author style sheet
  2. User style sheet
  3. User-agent (browser) stylesheet

Importance:

  1. Normal declaration (p {color: red} )
  2. Important declaration (p {color: red !important} )

!important

The !important value appended in a declaration along with the property value in any of the ruleset/rules will be taken as the most priority even if the rule has less specificity.

Override !important:

Either add Specificity to the declaration or have only one !important declaration, remove others.

Cascade Order:

        The cascading order depends on origin, specificity, importance and source order. Below is the precedence order from low to high,

  1. Declarations in user agent style sheets (e.g. the browser’s default styles, used when no other styling is set).
  2. Normal declarations in user style sheets (custom styles set by a user).
  3. Normal declarations in author style sheets (these are the styles set by the web developers).
  4. Important declarations in author style sheets
  5. Important declarations in user style sheets

Note:

  • Declaration with Same Importance and Same-Origin: More specific selectors will override more general ones
  • Source Order – Declaration with the Same Importance, Same Specificity, and Same-Origin: the later rule takes precedence

Best Practices:

  • Use Class selectors instead of ID selectors.
  • Avoid using multiple CSS rules that target the same HTML elements.
  • Do not use inline styles.
  • Use specificity before even considering !important .
  • Although ‘!important’ works, it is generally bad practice. It can make debugging a difficult process
  • Only use !important on page-specific CSS that overrides foreign CSS (from external libraries, like Bootstrap or normalize.css).

Reference:

1) https://www.w3.org/TR/2011/REC-CSS2-20110607/cascade.html#cascade
2) https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
3) https://css-tricks.com/precedence-css-order-css-matters/
4) https://vanseodesign.com/css/css-specificity-inheritance-cascaade/
5) https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Cascade_and_inheritance
6) http://tutorials.jenkov.com/css/precedence.html