rxjs observable code example

Example 1: emit new value observable

const observable = new BehaviorSubject("initial value");

observable.subscribe({
    next: (value) => console.log("The value is: ", value)
});

observable.next("a new value");

Example 2: rxjs .subscribe

content_copy
      
      
        open_in_new
      
      import { interval } from 'rxjs';

const observable = interval(1000);
const subscription = observable.subscribe(x => console.log(x));
// Later:
// This cancels the ongoing Observable execution which
// was started by calling subscribe with an Observer.
subscription.unsubscribe();

Example 3: rxjs create observable from value

// Requires RXJS 6+
// Create an observable of any Type
// Ask yourself if the function creates a new observable or not
// If it creates a new one then it is imported from 'rxjs'
// Operators are imported from 'rxjs/operators'
import { of } from 'rxjs';

// T => Observable<T>
const value$ = of(1);

Example 4: create an observabloe js

content_copy
      
      
        open_in_new
      
      function foo() {
  console.log('Hello');
  return 42;
}

const x = foo.call(); // same as foo()
console.log(x);
const y = foo.call(); // same as foo()
console.log(y);