Angular Js

How many different ways we can create an observable in Angular?

How many different ways we can create an observable in Angular?

Different ways we can create an observable in Angular?

This Article helps you to Understand, How many different ways we can create an observable in Angular?


Observables are like functions with zero arguments that push multiple values to their Observers, either synchronously or asynchronously.

In Angular, observables may be created in a variety of ways., you can utilise the observable Constructor for this. You can build new observables using a variety of operators that are provided. We can generate an observable from an array, string, promise, any iterable, etc. with the use of these operators.

All the creation related operators are part of the RxJs core library. You can import it from the ‘rxjs’ library


Create Method

One of the simplest approaches is by using create method. Behind the scenes, the create method invokes the observable Constructor. There is no need to import Create because it is a method of the observable object.


ngOnInit() {

  //Observable from Create Method
  const obj= Observable.create( observer => {
    observer.next( '1' )
    observer.next( '2' )
    observer.next( '3' )

    observer.complete()
  })

  obj.subscribe(
val => console.log(val),
  error => console.log("error"),
    () => console.log("complete"))
}

// Output
1
2
3
Complete


Observable Constructor

There is no difference between the Observable.create method and observable constructor. The Create method calls the constructor behind the scene.


ngOnInit() {

  //Observable Using Constructor
  const obj = new Observable( observer => {
     observer.next( '1' )
     observer.next( '2' )
     observer.next( '3' )

     observer.complete()
  })

  obj.subscribe(
val => console.log(val),
     error=> console.log("error"),
     () => console.log("complete"))
}

Work same as above


Of Operator

The observable is created by the Of operator from the arguments you supply. The Of operator accepts any number of parameters. The arguments were each emitted in turn, one after the other. In the end, it sends the Complete signal.


1. observable from an array
===========================
import { of } from 'rxjs';

ngOnInit() {
  const array=[1,2,3,4,5,6,7]
  const obj=of(array);

  obj.subscribe(
val => console.log(val),
     error=> console.log("error"),
     () => console.log("complete"))
 
//Output
[1, 2, 3, 4, 5, 6, 7]
complete




2. We can pass more than one array
==================================
ngOnInit() {
  const array1=[1,2,3,4,5,6,7]
  const array2=['a','b','c','d','e','f','g']

  const obj=of(array1,array2 );
  obj.subscribe(
      val => console.log(val),
      error=> console.log("error"),
      () => console.log("complete"))
}

//Output
[1, 2, 3, 4, 5, 6, 7]
['a','b','c','d','e','f','g']
complete
 



3. observable from a sequence of numbers
========================================
ngOnInit() {
  const obj = of(1, 2, 3);
  obj.subscribe(
val => console.log(val),
    error => console.log("error"),
    () => console.log("complete"))
}

//Output
1
2
3
complete



4. observable from string
=========================
ngOnInit() {
    const obj = of('Hello', 'World');
    obj.subscribe(
val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
}


// Output
Hello
World
complete


From Operator

From Operator takes only one argument that can be iterated and converts it into an observable.
You can use it to convert

  • an Array
  • anything that behaves like an array
  • Promise
  • any iterable object
  • collections
  • any observable like object
  • It converts almost anything that can be iterated to an Observable.

1. Observable from array

import { from } from 'rxjs';
ngOnInit() {
    const array = [1, 2, 3, 4, 5, 6, 7]
    const obj = from(array);
    obj.subscribe(
val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
}

// Output
1
2
3
4
5
6
7
complete




2. Observable from string

ngOnInit() {
    const obj = from('Hello World');

    obj.subscribe(
val => console.log(val),
        error => console.log("error"),
        () => console.log("complete"))
}
     
// Output
  H
  e
  l
  l
  o
   
  W
  o
  r
  l
  d
  complete




3. Observable from collection

ngOnInit() {
      let myMap = new Map()
      myMap.set(0, 'Hello')
      myMap.set(1, 'World')
      const obj = from(myMap);

      obj.subscribe(
val => console.log(val),
        error => console.log("error"),
        () => console.log("complete"))
)

// Output
[0, "Hello"]
[1, "World"]
complete



4. Observable from iterable
Any Iterable types like Generator functions can be converted into an observable using from the operator.

ngOnInit() {
    const obj = from(this.generateNos())

    obj.subscribe(
val => console.log(val),
     error => console.log("error"),
     () => console.log("complete"))
}

generateNos() {
  var i = 0;
  while (i < 5) {
    i = i + 1;
    yield i;
}


// Output
1
2
3
4
5



Observable from promise

Use it to convert a Promise to an observable


ngOnInit() {
    const promise = from(new Promise(resolve => resolve('Hello World!')));

    const obj = from(promise);
    obj.subscribe(
val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
}

// Output
Hello World
complete






Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram