Skip to content

Instantly share code, notes, and snippets.

@rlunaro
Last active October 3, 2022 06:41
Show Gist options
  • Save rlunaro/971ec24ca9ded755ba9c14b47561822d to your computer and use it in GitHub Desktop.
Save rlunaro/971ec24ca9ded755ba9c14b47561822d to your computer and use it in GitHub Desktop.
Notes on Observables

Notes on Observables

Intro

The basic pattern of the observable or observer, and has two parts:

  • The observable itself, that is, the object hat emits changes to any observer that wants to listen to it
  • The observers, objecst who get called any time the observable emits a change

Simple example

import { Observable, Subscription } from 'rxjs'; 

const customObservable = new Observable( (observer) => {
  let count = 0;  
  setInterval( () => {
    if( count === 70 )
      observer.error( new Error( count + ' is found' ) );
    if( count === 13 )
      observer.complete();
    observer.next( count );
    count++;
  }, 1000 );
});

this.subscription = customObservable.subscribe( (count) => {
  console.log( 'the value of count is ', count );
}, (error) => {
  console.log( error );
}, () => {
  console.log( 'observable is finalized' );
});

With operators and the new subscribe format

import { Observable, Subscription, map } from 'rxjs'; 

const customObservable = new Observable( (observer) => {
  let count = 0;
  let stopIntervalValue = null;
  stopIntervalValue = setInterval( () => {
    console.log( "## count: ", count );
    if( count === 70 )
      observer.error( new Error( count + ' is found' ) );
    if( count === 13 ){
      observer.complete();
      clearInterval( stopIntervalValue );
    }
    observer.next( count );
    count++;
  }, 1000 );
});

const pipedObservable = customObservable.pipe( map( (data : number) => {
  return 'Round: ' + (data + 1);
}) );

this.subscription = pipedObservable.subscribe({
  next : (count) => {
    console.log( 'the value of count is ', count );
  },
  error : (error) => {
    console.log( error );
  },
  complete : () => {
    console.log( 'observable is finalized' );
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment