Of and from - RXJS Operator

Of and from - RXJS Operator

In this tutorial, we will learn about Of and from operator of RXJS.

Of Operator

  The of Operator is a creation Operator. Creation Operators are functions that create an Observable stream from a source.  

Of() operator converts the arguments to an observable sequence

const arr = [1, 2, 3];

const arr$ = of(arr);

arr$.subscribe((values) => console.log(values));
//Output: 
1
2
3

Example-2:

onst obs1 = of("Jigar", "Shekhar", "Shara");
obs1.subscribe((res) => {
      console.log(res);
});

//Output: 
Jigar
Shekhar
Shara

from Operator

The from Operator turns an Array, Promise, or Iterable, into an Observable.

The from() operator allows us to create an Observable from some other asynchronous/synchronous concept. It's really powerful when almost anything (array, promise, or iterable) can be made into an Observable

From() Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.

import { from } from 'rxjs';

let source = from([1,2,3,4]);

source.subscribe( data => console.log(data)); 
//output: 
1
2
3
4

Example-2: Convert Promise to Observable

const promise = new Promise((resolve) => {
      setTimeout(() => {
        resolve("Promise Resolved");
      }, 3000);
    });

    const obs = from(promise);
    obs.subscribe((res) => {
      console.log("From Promise => ", res);
    });

Output:
From Promise =>  Promise Resolved

Example-3: Using with String

const obs = from("Welcome");
    obs.subscribe((res) => {
      console.log("From String => ", res);
    });

OutPut:
From String =>  W
From String =>  e
From String =>  l
From String =>  c
From String =>  o
From String =>  m
From String =>  e

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like

Leave a Comment