In the previous post we saw the basics about observables, observers, and subscriptions. In this post we will expand a bit on the nature of observables, and different ways to create them using Angular.

So far we have seen observables as data producers: there is more to it than that, but for a little longer let’s keep looking at them as this black box that emits data and see a few different ways to create an observer.

We already have seen how we can use from to convert an array into an observable. We have various function that allows to create or convert stuff into observables. Very similar to from we have of. The of function converts a list of arguments into an observable sequence:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { of, Subscription } from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit, OnDestroy{
  private _mySubscription: Subscription;

  public ngOnInit() {

    let observable = of('message 1', 'message 2','message 3');

    this._mySubscription = observable.subscribe((x:string) => {
        console.log(`Received message: ${x}`);
      }
     );
  }

  public ngOnDestroy() {
    this._mySubscription.unsubscribe();
  }
}

But more interesting is that we can also convert into observables this:

  • Promises
  • Events
  • Functions

Convert a Promise into an Observable

To convert a Promise into an observable we can use again the from function:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { from, Subscription } from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit, OnDestroy{
  private _mySubscription: Subscription;

  public ngOnInit() {

    var promise:Promise = new Promise((resolve, reject) => {
      resolve(true);
    });

    let observable = from(promise);

    this._mySubscription = observable.subscribe((x:boolean) => { 
        console.log(`Promise resolved to: ${x}`);
      }
     );
  }

  public ngOnDestroy() {
    this._mySubscription.unsubscribe();
  }
}

Create an angular Observable from an event

fromEvent is a function that allows us to turn an event in an observable sequence. Let’s write a code example in which we are going to subscribe to a mouse ‘click’ event:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { fromEvent, Subscription } from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit, OnDestroy{
  private _mySubscription: Subscription;

  public ngOnInit() {

    var input = document.getElementById('identifier1');
    let observable = fromEvent(input, 'click');

    this._mySubscription = observable.subscribe((x:MouseEvent) => {
        console.log(`Component clicked at position ${x.clientX}, ${x.clientY}`);
      }
     );
  }

  public ngOnDestroy() {
    this._mySubscription.unsubscribe();
  }
}

We started by creating an observable using the fromEvent function:the first parameter is the DOM element we are listening to, and the second parameter the type of event we want to listen (ins this case “click”, but we could listen to “mouseover”,”keydown”,etc)

var input = document.getElementById('identifier1');
let observable = fromEvent(input, 'click');

Next we subscribe as usual to the observable: I implement the next handler, so that when a click events occur I display in cosole a message showing the x/y coordinates:

 this._mySubscription = observable.subscribe((x:MouseEvent) => {
        console.log(`Component clicked at position ${x.clientX}, ${x.clientY}`);
      }
     );

Remember also to dispose the subscription when you do not longer need it:

  public ngOnDestroy() {
    this._mySubscription.unsubscribe();
  }

So the code above will listen when someone clicks in the DOM element with id identifier1 and write a message to console when that happens.

For completion sake let’s also post the HTML DOM of the component, and its css:

<div id="identifier1">An html component</div>
#identifier1{
    width:200px;
    height:200px;
    background-color: bisque;
    border: 1px;
    border-style: double;
}

When we put it all together I get in my browser a not so beautiful colored box that writes a message in the console every time I clicked it:
fromEvent, convert javascript DOM event in an observable

Create an observable using a subscribe function

We can also use the create method to produce an observable. This method takes as a parameter a subscription method, and works like this:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { Observable, Subscription, PartialObserver } from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy{
  private _mySubscription: Subscription;

  public ngOnInit() {

    let observable:Observable = Observable.create((observer:PartialObserver)=> {
      observer.next('Hello world');
      observer.next('How are you?');
      observer.complete();
    });

    this._mySubscription = observable.subscribe((x:string) => { 
        console.log(`Message received: ${x}`);
      }
     );
  }

  public ngOnDestroy() {
    this._mySubscription.unsubscribe();
  }
}

That’s all for today, thanks for reading 🙂

Advertisements