RxJS Introductions - The first steps

Introduction

This is a essential part of Reactive programming.

An observable represents a stream, or source of data that can arrive over time.

The most common use case in RxJS is from events. This can be anything from mouse moves, button clicks, input into a text field, or even route changes.

Observables are cold, or do not activate a producer until there is a Subscription.

To create a subscription, you call the subscribe method, supplying a function (or object) - also known as an observer.

// import the fromEvent operator
import { fromEvent } from 'rxjs';

// grab button reference
const button = document.getElementById('myButton');

// create an observable of button clicks
const myObservable = fromEvent(button, 'click');

// for now, let's just log the event on each click
const subscription = myObservable.subscribe(event => console.log(event));


.subscribe() function is used to subscribe to the observable. This function will set up an event listener, call the function (passed inside subscriber function) whenever the event happens and returns the subscription object with an unsubscribe object.

Unsubscribe contains the clean up logic like remove the appropriate event listener.

Each subscribe() will create a new executable context.

Subscribe function takes object of next, error and complete functions. Next function is invoked when successful emission occurs from the observable.

// instead of a function, we will pass an object with next, error, and complete methods
const subscription = myObservable.subscribe({
  // on successful emissions
  next: event => console.log(event),
  // on errors
  error: error => console.log(error),
  // called once on completion
  complete: () => console.log('complete!')
});


Subscription in this scenario is called Unicasting i.e. it creates a one direction flow where observable emits to the subscriber. (Think for an example a Face to Face interview with one person)

Operators

Operators offer a way to manipulate values from a source, returning an observable of the transformed values.



Let's talk about the Pipe function.
The pipe function is the assembly line from your observable data source through your operators.

Imagine the pipe function as a chain of operators where you can manipulate, filter, and transform the data to fit your use case.

inputValue
  .pipe(
    // wait for a 200ms pause
    debounceTime(200),
    // if the value is the same, ignore
    distinctUntilChanged(),
    // if an updated value comes through while request is still active cancel previous request and 'switch' to new observable
    switchMap(searchTerm => typeaheadApi.search(term))
  )
  // create a subscription
  .subscribe(results => {
    // update the dom
  });

You must know that these operators are divided into categories that suits the needs. These categories are:
  1. Creation Operators
    These operators allows creation of an observable from nearly anything.
    Example: suppose we are creating a progress bar as a user scrolls through an article. We could turn the scroll event into a stream by utilizing the fromEvent operator
    The most commonly used creation operators are offrom, and fromEvent.
  2. Combination Operators
    The combination operators allow the joining of information from multiple observables.
    The most commonly used combination operators are combineLatestconcatmergestartWith, andwithLatestFrom.
  3. Error Handling OperatorsThe error handling operators provide effective ways to gracefully handle errors and perform retries, should they occur.
    For example, we can use catchError to safeguard against failed network requests.The most commonly used error handling operators is catchError.
  4. Filtering Operators
    The filtering operators provide techniques for accepting - or declining - values from an observable source and dealing with backpressure, or the build up of values within a stream.
    The most commonly used filtering operators are debounceTimedistinctUntilChangedfiltertake, and takeUntil.
  5. Multicasting Operators
    In RxJS observables are unicasting by default. These operators can make an observable hot, or multicast, allowing side-effects to be shared among multiple subscribers.
    The most commonly used multicasting operator is shareReplay.

  6. Transformational Operators
    These operators provide transformation techniques for nearly any use-case you will encounter.
    The most commonly used transformation operators are concatMapmapmergeMapscan, andswitchMap.
At this stage, these categories can look quite scary. Don't worry you all, it will soon click once you keep coding with this library.
While operators can be grouped into common categories, operators within a category often share common behavior. By recognizing this common behavior you can start creating a 'choose your own operator' tree in your mind.

Comments

Popular posts from this blog

ASP.NET Core 2.x - Getting Started