Referencedefer
Reference · 06
defer
defer
Creates an Observable "lazily" — the factory runs on every subscription.
Signature
defer(observableFactory: () => ObservableInput): Observable
What it does
Defers creating the Observable until subscribe. Each subscriber gets a "fresh" Observable from the factory. This makes values that would otherwise be fixed at creation time (Date.now, new Promise(...), random) truly lazy.
When to use
You need a new Promise/HTTP request per subscriber. You need data that's current at subscription time, not at pipe-configuration time. You want to turn ordinary code into a cold Observable.
Gotcha
of(fetch('/api')) creates one Promise when the module loads. defer(() => fetch('/api')) creates one per subscription.
See also
from, iif, shareReplay
script.ts
CONSOLE · Console output
Hit Run to see the result...