1. Why RxJS in Angular
Welcome to RxJS
This is the very first lesson. If you've never touched RxJS, don't worry — we'll start from the simplest idea and move in small steps. By the end you'll understand what a stream, an Observable, and a subscription are, and you'll have written your first working example.
What problem does RxJS solve
In ordinary code we're used to one thing: a variable holds a single value right now. But real apps are different — values arrive over time:
- A user clicks a button — the event arrives whenever they do.
- A user types in a search box — each keystroke arrives on its own.
- A server answers an HTTP request — the response comes back after a while.
- A timer ticks every second — values arrive at a steady beat.
RxJS gives you one consistent way to handle all of these sources. That way is called a stream.
Glossary: the key terms
- Stream — a sequence of values that show up over time. Picture a conveyor belt: boxes appear on it at intervals.
- Observable — the RxJS object that describes a stream. On its own it does nothing; it's just a recipe for where the data comes from.
- Subscribe — the moment you say "start sending me values." Until you subscribe, an Observable stays silent.
- Subscriber — the function that receives each value. It's the callback inside
subscribe(...). - The
ofoperator — the simplest way to build an Observable from a handful of ready-made values.
A quick worked example
of('click', 'http', 'timer').subscribe(value => console.log(value));
Read it left to right: "make a stream of three values → subscribe → log each value to the console." Three lines show up: click, http, timer.
Your task
- The starter code already has
const events$ = of();— but it's empty. Pass three strings intoof(...):'click','http','timer'(comma-separated). - Inside
subscribe, addconsole.log('Event: ' + value)— that turns each value into a prefixed string. - Run the code. Three lines should appear in the console, in that order.
A naming convention: Observable variables are usually named with a trailing $. It's purely a visual cue — it means nothing special to JavaScript.
Important for the check
The check compares the output lines exactly: same text, same order, no extra logs. Add a stray console.log and it won't pass.
const { of } = Rx;
const events$ = of('click', 'http', 'timer');
events$.subscribe(value => {
console.log('Event: ' + value);
});