Skip to content
This repository was archived by the owner on Dec 5, 2024. It is now read-only.

1 introduction

Gregor Woiwode edited this page Apr 29, 2021 · 3 revisions

Table of contents generated with markdown-toc

Push numbers

  • Open apps/playground/src/index.ts
  • Create an observable
  • Subscribe to the observable
  • Push the numbers 1, 2, 3, 4
  • Then complete
  • Check the output
  • Try pushing a value after complete
  • Try throwing an error with the text something went wrong
  • run npm run start:playground to start the app

Hints

import { Observable } from 'rxjs';

// Create observable
const helloWorld$ = new Observable(
  function subscribe(observer) {
    observer.next('Hello');
    observer.next('World');
    observer.complete();
  }
);

// Subscribe to an observable
helloWorld$.subscribe({
  next(x) {console.log(x);},
  error(err) {console.error(err);},
  complete() {console.log('done');}
});

Add a delay

  • Push a value in a 1 second interval

Hints

// do something every second
setInterval(() => console.log('every second'), 1000);

Unsubscribe

  • Clear the interval when unsubscribe is called
  • Don't forget to wait some seconds before you unsubscribe

Hints

// do something every second
const interval = setInterval(() => console.log('every second'), 1000);

// stop interval
clearInterval(interval);

// wait 5 seconds before doing something
setTimeout(() => {
  console.log('after 5 seconds');
}, 5000);

Try timer

  • Push a value every 2 seconds
  • Wait 5 seconds before pushing the first value
  • Check the output

Hints

import { timer } from 'rxjs';

const dueTime = 1000;
const period = 1000;

const observable$ = timer(dueTime, period);
Clone this wiki locally