Lesson 33 of 56 · Typescript
RxJS Typing
Duration: 20 minutes
Observable with Generics
import { Observable } from 'rxjs';
function numbers(): Observable<number> {
return new Observable<number>(subscriber => {
let i = 0;
const id = setInterval(() => subscriber.next(i++), 1000);
return () => clearInterval(id);
});
}
Operators typing
import { map, filter } from 'rxjs/operators';
numbers()
.pipe(
filter(n => n % 2 === 0),
map(n => `Even: ${n}`)
)
.subscribe(console.log);
Subject as a typed event bus
import { Subject } from 'rxjs';
type Message = { type: 'info' | 'error'; payload: string };
const bus = new Subject<Message>();
bus.next({ type: 'info', payload: 'hello' });