LiveLoveApp logo

Creation Operators

Creation Operators

  • Creation operators are pure functions that create new observables
  • They are not pipeable
  • RxJS ships with a handful of creation operators to handle common use cases

of

  • Creates an observable that emits each item in the order they were provided
  • Helpful for demos, or for wrapping values in an observable
of(1, 2, 3).subscribe((value) => console.log(value));

throwError

  • Creates an observable that throws the provided value
  • Like of, but for errors!
throwError(new Error('Error!')).subscribe(
  (value) => console.log(value),
  (error) => console.error(error)
);

fromEvent

  • Use fromEvent to listen to events on event targets
  • Especially useful for listening to DOM events on HTML elements
<button>Click Me!</button>
const button = document.querySelector('button');

fromEvent(button, 'click').subscribe(...)

timer

  • Creates an observable that emits after a specified period
  • Observable equivalent of window.setTimeout(...)
timer(1_500).subscribe(...)

interval

  • Creates an observable that emits on a specified time interval
  • Observable equivalent of window.setInterval(...)
interval(500).subscribe(...)

from

  • Converts almost anything into an observable
  • Works on arrays, iterables, and promises

from on Arrays

import { from } from 'rxjs';

const values = [1, 2, 3]

from(values).subscribe(...)

from on Iterables

function* getChars() {
  yield 'a';
  yield 'b';
  yield 'c';
}

from(getChars()).subscribe(...);

from on Promises

from(
  fetch('http://example.com/movies.json')
).subscribe(...)

Note on ObservableLike

  • from works on things that are observable-like
  • Arrays, promises, iterables, and other observables are considered observable-like
  • This will be important for more advanced operators

ajax

Observable wrapper for making AJAX requests:

ajax('http://example.com/movies.json');

Getting JSON:

ajax.getJSON('http://example.com/movies.json');