Skip to content

Instantly share code, notes, and snippets.

View cartant's full-sized avatar

Nicholas Jamieson cartant

View GitHub Profile
import { interval, timer } from "rxjs";
import { shareReplay, takeUntil } from "rxjs/operators";
import { log } from "./log";
const source = log(interval(100), "source");
const shared = log(source.pipe(shareReplay(1)), "shared");
shared.pipe(
takeUntil(timer(150))
).subscribe(
import { timer } from "rxjs";
import { shareReplay, takeUntil } from "rxjs/operators";
import { log } from "./log";
const source = log(timer(100), "source");
const shared = log(source.pipe(shareReplay(1)), "shared");
shared.pipe(
takeUntil(timer(50))
).subscribe(
import { range } from "rxjs";
import { debug } from "./debug";
const source = range(1, 2).pipe(debug());
console.log("first use:");
source.subscribe();
console.log("second use:");
source.subscribe();
import { range } from "rxjs";
import { debug } from "./debug";
const op = debug();
console.log("first use:");
range(1, 2).pipe(op).subscribe();
console.log("second use:");
range(1, 2).pipe(op).subscribe();
import { MonoTypeOperatorFunction } from "rxjs";
import { map, scan } from "rxjs/operators";
export function debug<T>(): MonoTypeOperatorFunction<T> {
return source => source.pipe(
scan<T, [T, number]>(([, index], t) => [t, index + 1], [undefined!, -1]),
map(([t, index]) => (console.log(`[${index}]: ${t}`), t))
);
}
import { defer, MonoTypeOperatorFunction } from "rxjs";
import { tap } from "rxjs/operators";
export function debug<T>(): MonoTypeOperatorFunction<T> {
return source => defer(() => {
let index = -1;
return source.pipe(
tap(t => console.log(`[${++index}]: ${t}`))
);
});
import { MonoTypeOperatorFunction, Observable } from "rxjs";
import { tap } from "rxjs/operators";
export function debug<T>(): MonoTypeOperatorFunction<T> {
return source => new Observable<T>(subscriber => {
let index = -1;
return source.pipe(
tap(t => console.log(`[${++index}]: ${t}`))
).subscribe(subscriber);
});
import { MonoTypeOperatorFunction } from "rxjs";
import { tap } from "rxjs/operators";
export function debug<T>(): MonoTypeOperatorFunction<T> {
let index = -1;
// Let's pretend that the map operator doesn't exist and that we have to use
// the tap operator and maintain our own internal state for the index, as the
// purpose of our operator is to show that the behaviour depends upon where
// the state is stored.
return tap(t => console.log(`[${++index}]: ${t}`));
return this.http.get<Something>("https://api.some.com/things/1").pipe(
map(this.extractSomeProperty.bind(this)),
catchError(this.handleError.bind(this))
);
return this.http.get<Something>("https://api.some.com/things/1").pipe(
map(s => this.extractSomeProperty(s)),
catchError(e => this.handleError(e))
);