Category Archives: JavaScript

JavaScript

Rxjs 5: In 5 minutes!

Asynchronous programming was never so easy.

 

What is Reactive Programming?

An API for asynchronous programming
with observable streams.

What is stream, observable ?

Let’s dive in.

Key concepts —

  1. Stream
  2. Observable
  3. Observer
  4. Subscription
  5. Operator
  6. Subject

Stream

A stream is a sequence of data elements made available over time. A stream can be thought of as items on a conveyor belt being processed one at a time rather than in large batches. — Wikipedia

Alternatively, We can say that the stream is a sequence of ongoing events ordered in time. For example number of button click(s) in 1 Second. So all clicks will be grouped as a stream.

Stream in RxJs

In RxJS, we can create streams using —

  • From one or multiple values
  • From array of values
  • From an event
  • From a Promise
  • From a callback

Thats it! This much understanding about stream is enough to proceed.

Well, our main goal is to operate on such streams. Means, The stream is the subject which being observed.

Observable

With official doc, its might be hard for you to understand what is Observable. But Ben Lesh(RxJS 5+ Lead) made it super easy for us. See this great post by him.

Learning Observable By Building Observable by Ben Lesh

Additionally let’s read official Observable page.

Lets create one —

var myObservable = Rx.Observable.create(function (observer) {
  observer.next(1);
  observer.next(2);
  observer.next(3);
  setTimeout(() => {
    observer.next(4);
    observer.complete();
  }, 1000);
});

console.log('just before subscribe');
myObservable.subscribe({
  next: x => console.log('got value ' + x),
  error: err => console.error('something wrong occurred: ' + err),
  complete: () => console.log('done'),
});
console.log('just after subscribe');

Now you know that,

  • Observable is a representation of stream to operate on later.
  • We can create custom observable using Rx.Observable.create method, which returns and object having subscribe method on it.
  • subscribe method takes an object as a param which is nothing but observer.
  • Observer: An object with `next`, `error` and `complete` methods on it. Or Just an `next` function. Just like this —
/* With an observer */
var observer = Rx.Observer.create(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  }
);
// Or just an next function like then() in promises
var observer = (x) => {
  console.log('Completed');
}

Rx.Observable class has many functions to create observables from different kind of data/streams such as events, event patterns, arrays, promises, single/multiple value, any kind of data structure/primitive data types and so on.

Examples –

// From event
var clicks = Rx.Observable.fromEvent(document, 'click'); clicks.subscribe(x => console.log(x));  
// Results in: 
// MouseEvent object logged to console every time a click 
// occurs on the document.

// Converts an array to an Observable
var array = [10, 20, 30]; 
var result = Rx.Observable.from(array); 
result.subscribe(x => console.log(x));  
// Results in the following: 
// 10 20 30

// Convert the Promise returned by Fetch to an Observable
var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
result.subscribe(x => console.log(x), e => console.error(e));
----------------------------------------------
result.subscribe({
  next: x => console.log('got value ' + x),
  error: err => console.error('something wrong occurred: ' + err),
  complete: () => console.log('done'),
});
// Or just next fn
result.subscribe((x) => {
  console.log('got value ' + x)
})

Subscription

The “listening” to the stream is called subscribing.

Calling subscribe method of Observable we can listen to stream.

To invoke the Observable, we need to subscribe to it.

Just creating Observables will not going to listen streams, we must have to invoke the Observable by calling subscribe method.

For example —

var clicks = Rx.Observable.fromEvent(document, 'click');
// Subscribe to observable 
// so that we can listen stream changes
let clicksSubscription = clicks.subscribe(x => {
  console.log(x)
});
// Later we can stop listening to streams 
clicksSubscription.unsubscribe();

Operators

Now we have Observables. Lets understand Operator.

Now again read/remember “Operators: Also Just Functions” section from this article by Ben Lesh. He greatly explained about what is Operator. Just read and then come back here.

Done ? Great!

Now hell you know that,

  • A pure function which takes one Observable as input and generates another Observable as output.
  • Subscribing to the output Observable will also subscribe to the input Observable.

Think Operators as an Lodash functions.

Lets create one custom operator function that multiplies each value received from the input Observable by 10

function multiplyByTen(input) {
  var output = Rx.Observable.create(function subscribe(observer) {
    input.subscribe({
      next: (v) => observer.next(10 * v),
      error: (err) => observer.error(err),
      complete: () => observer.complete()
    });
  });
  return output;
}

var input = Rx.Observable.from([1, 2, 3, 4]);
var output = multiplyByTen(input);
output.subscribe(x => console.log(x));
// Result In:
// 10 
// 20 
// 30 
// 40

There are operators for different purposes, and they may be categorized as: creation, transformation, filtering, combination, multicasting, error handling, utility, etc. here you will find all of them.

You can visit official website and choose operators as per your need.

Some examples –

1. Get the maximal value of a series of number
Rx.Observable.of(5, 4, 7, 2, 8)   
.max()   
.subscribe(x => console.log(x));
// Result In: 8
2. Map every click to the clientX position of that click
var clicks = Rx.Observable.fromEvent(document, 'click'); 
var positions = clicks.map(ev => ev.clientX); 
positions.subscribe(x => console.log(x));
3. Chaining operators
const input = Rx.Observable.fromEvent(node, 'input')
.map(event => event.target.value)
.filter(value => value.length >= 2)
.subscribe(value => {
  // use the `value`
});

Chaining operators

Each operator in the chain modifies the Observable that results from the operation of the previous operator.

Subject

In RxJs-

  • Plain Observables are unicast.
  • Subject is a special type of Observable that allows values to be multicasted to many Observers.
  • Subjects maintain a registry of many listeners/sunscriber.

Lets understand unicasting vs multicasting first!

Unicast: A transmission/stream sends IP packets to a single recipient on a network.

Example :- Plain Observable

Explanation:- you have to do .subscribe(). If you subscribe multiple times against the original observable, you are not sharing the original observable. You are creating a new observable every time you subscribe.

Multicast: A transmission sends IP packets to a group of hosts on a network.

Example :- RxJs Subject, Promises

Explanation:- You have to do .subscribe() as many times as you want against that original observable.

Wants to dive deeper ?

Again thank you to Ben Lesh. Lets have a look at “Rx Subjects” section from this article.

Thats it!

I hope you enjoyed this article and it was worth reading!

Also don’t forget to give me a 👏 so that it will be the message for others.

Credits —

Advertisements

Analyzing the Bundle Size & Code splitting in Create React App

 

react-loadable-webpack

TLDR: You can clone/download cra-boilerplate from github and see how Code splitting is implemented.  

Create React App(CRA) by default bundle out entire app into single main.*.js file with Webpack. As our app grows, bundle grows. Bundling is the process of following imported files and merging them into a single file: a “bundle”.

So instead of downloading the entire app(This hurts the initial load time of our app.) before users can use it, We can split code into small chunks which we can then load on demand and Code splitting is really helpful for larger React apps.

Continue reading Analyzing the Bundle Size & Code splitting in Create React App

Integrating create-react-app, Redux, React Router, Redux observable & Bootstrap altogether

TLDR; You can clone the example project to quick start from GitHub repo and walk through codebase.

image

create-react-app (CRA) is awesome with the power of react-scripts.

Although when it comes to complicated single-page applications, we need –

  • Routing
  • Central state/data container like local storage
  • Aysnc actions handler
  • UI framework
  • CSS preprocessors… and so on as per individual need.

Now lets dive in to create one full fledged single-page application with CRA and other great libraries.

Continue reading Integrating create-react-app, Redux, React Router, Redux observable & Bootstrap altogether

How to keep up to date on front end technologies

Hello there, can i ask you simple question ?

Why do we need to learn new tools, keeps our eyes on latest trends and workflows in our industry ?

The simplest answer would be – We don’t want to be outdated.

Right ? as you know that the web is a rapidly evolving universe and its vital part of our job is to stay updated with latest tools, trends, workflows, frameworks  …and so on in web industry.

Continue reading How to keep up to date on front end technologies

Backbone js load Async Template files

Template Manager plugin for Loading HBS template files:

file: templateManager.js

/*
  templateManager - Async Handlebars template loader/cacher.
  @author Mohan Dere
  @version 1.0
  @requires jQuery || zepto, underscore, Handlebars.js
*/


(function() {

  window.TemplateManager = (function() {
    var cache, defaults, fetchAndCache;

    defaults = {
      path: '/tpl/',
      ext: '.hbs'
    };

    cache = {};

    function TemplateManager(options) {
      this.options = options != null ? options : {};
      _.defaults(this.options, defaults);
      if (this.options.cache) {
        cache = this.options.cache;
      }
    }

    TemplateManager.prototype.load = function(tpl, callback) {
      if (_.has(cache, tpl)) {
        return callback(cache[tpl]);
      }
      tpl = fetchAndCache.apply(this, arguments);
      if (!callback) {
        return tpl;
      }
      return tpl.done(function(tplString) {
        if (callback) {
          return callback(tplString);
        }
      });
    };

    fetchAndCache = function(tpl) {
      var deferred, tplPath,
        _this = this;
      deferred = new jQuery.Deferred();
      tplPath = "" + this.options.path + tpl + this.options.ext;
      jQuery.ajax({
        url: tplPath,
        type: 'GET',
        dataType: 'text',
        success: function(tplString) {
          cache[tpl] = Handlebars.compile(tplString)
          cache[tpl].tplString = tplString;
          return deferred.resolve(cache[tpl]);
        }
      });
      return deferred;
    };

    return TemplateManager;

  })();

}).call(this);

Usage:

// Create the WordPress Backbone namespace.
var jwfpApp = {
    _views: {},
    _models: {},
    _collections: {},
    _vent: _.clone(Backbone.Events),
    tpl: new TemplateManager({
    path: jwfpAppData.tpl_path
  })
};

// Inside view file and in render function

var self = this;
jwfpApp.tpl.load('tpl/homePage', function(template) {
  self.$stageConatiner.html(template({});
});