RxJS of() and from() operator

In RxJS, to and from are functions used to create observables from various data sources or data structures.

from:

  • The from function is used to create an observable from an array, iterable, promise, or another observable-like object.
  • It takes an array, iterable, promise, or observable-like object as an argument and returns an observable that emits each item from the source data structure.
  • Example:
import { from } from 'rxjs';

const array = [1, 2, 3, 4, 5];
const observable = from(array);

observable.subscribe(value => console.log(value)); // Output: 1, 2, 3, 4, 5

to:

  • The to function is used to convert an observable into another type or data structure.
  • It is often used in combination with other operators to convert observables into promises, arrays, or other data structures.
  • There is no native to function in RxJS. Instead, you may use operators like toArray, toPromise, or toPromiseArray to convert observable into arrays or promises.
  • Example:
import { from } from 'rxjs';
import { toArray } from 'rxjs/operators';

const array = [1, 2, 3, 4, 5];
const observable = from(array);

observable.pipe(
  toArray()
).subscribe(array => console.log(array)); // Output: [1, 2, 3, 4, 5]

of:

  • The of operator is used to create an observable that emits a sequence of values in the exact order specified as arguments.
  • It accepts a variable number of arguments and emits each argument value sequentially.
  • It's commonly used to create observables from static values or a fixed set of values.
  • of emits value synchronously.
  • Example:
import { of } from 'rxjs';

const source = of(1, 2, 3, 4, 5);
source.subscribe(value => console.log(value));
// Output: 1, 2, 3, 4, 5