RxJS 13 ๐ฃ Promise & Async/Await Interop โ Bridging Observables and Promises
Modern JavaScript developers often write asynchronous logic with async/await and native Promises. RxJS provides Observables as the core reactive primitive, but these two worlds do not speak the same language. When you try to pipe a Promise directly into an Observable pipeline, the result can be unpredictable: the stream may never emit, or it may swallow the Promiseโs resolution, or it may close prematurely after the first value. To keep your reactive code safe and predictable, RxJS supplies dedicated operatorsโfirstValueFrom and lastValueFromโthat transparently convert a single value from either an Observable or a Promise into the output of a downstream operator. These operators preserve the underlying streamโs lifecycle, forward cancellation signals, and error handling, making them the recommended bridge between async/await syntax and RxJS streams.
This chapter walks through the mechanics of those bridges, shows how to compose them with common operators such as switchMap, demonstrates proper teardown with AbortSignal, and highlights pitfalls that arise when you mix manual await inside .pipe(). By the end youโll understand when to extract a single value, how to keep a stream alive while waiting for a Promise, and how to cancel a request at the network layer without leaking resources.
Key point: firstValueFrom and lastValueFrom let you pull a single value out of an Observable or a Promise while keeping the whole stream alive, respecting cancellation and error paths, and avoiding the classic โoneโvalue vs manyโvaluesโ trap.
Why exists
The subscriber is a registered observer. When you call subscribe(), RxJS constructs a Subscriber object, passes it to the sourceโs subscribe function, and the source stores it in its internal observer list. That list lives until the source completes or the subscription is torn down. For finite sources (of, timer, first) the list empties automatically; for indefinite sources (interval, Subject, WebSocket, fetch) it stays populated forever unless someone explicitly removes the entry.
The async/await pressure. Modern codebases favor const result = await fetch(...); over chaining .then() callbacks. Mixing that style with RxJS pipelines creates mismatched lifetimes: the outer await resolves the entire pipeline, but the inner Observable still holds references to the component instance, DOM nodes, or HTTP connections. When the pipeline finishes, the Observableโs subscribers may remain attached to the source, causing duplicate requests or lingering listeners.
The platform boundary. Web APIs expose cancellation only via AbortController and AbortSignal. An Observable does not know whether the consumer wants one value or a million. Unwittingly, a switchMap might resubscribe after each value, recreating a new connection instead of cancelling the old one. Without explicit wiring, a cancelled request can linger in the network stack, leading to resource exhaustion.
Operator ownership confusion. Some operators already manage their own inner subscriptionsโswitchMap, exhaustMap, shareReplay. Writing teardown around them hides where the lifetime originates and makes debugging harder. Recognizing which operator owns its internals tells you whether you need to add any finalize or unsubscribe yourself.
Historical gaps. Early versions of RxJS treated Promises as opaque values rather than firstโclass streams. Even today, the official docs emphasize that firstValueFrom was introduced to solve exactly this interoperability gap. The change came with RxJSโฏ13, aligning the libraryโs type system with native Promise semantics.
These reasons make a dedicated tool needed: one that extracts a single value, forwards cancellation, preserves error propagation, and integrates cleanly with the rest of the pipeline.
Divider
a. What firstValueFrom and lastValueFrom do
Both operators are defined in rxjs/firstValueFrom and rxjs/lastValueFrom. Their signature accepts a source that can be either an Observable<T> or a Promise<T> and returns the first or last emitted value respectively. Internally they dispatch to the appropriate implementation:
import { firstValueFrom } from "rxjs";
import { lastValueFrom } from "rxjs";
// From an Observable
const first$ = of(1, 2, 3).pipe(firstValueFrom()); // โ 1
// From a Promise
const firstP = Promise.resolve(42).pipe(firstValueFrom()); // โ 42
If the source emits nothing, the operator returns undefined (for firstValueFrom) or undefined for lastValueFrom if the promise rejects. Errors propagate as usual: a rejected source becomes a rejection in the output, except when the source is a Promise that resolves to a nonโresolvable value.
b. Position in the pipeline
Place firstValueFrom after the source you want to inspect, but before any operator that consumes the value. Typical patterns:
source$.pipe(
firstValueFrom(),
map((v) => v * 2),
filter(v => v > 0)
).subscribe(handle);
Because firstValueFrom yields a single value, subsequent operators receive that value immediately, preventing the โmanyโvaluesโ explosion that mergeMap would cause.
c. Handling multiple values
When you need the last emitted item, reach for lastValueFrom:
const lastItem = some$.pipe(lastValueFrom()).subscribe(val => console.log("last:", val));
Or combine with reduce/scan after mapping:
some$.pipe(
map(v => v * 2),
lastValueFrom()
).subscribe(val => console.log(val));
Useful for tracking the most recent update, e.g., the current cursor position after a series of scroll events.
d. Integration with switchMap and other operators
switchMap cancels the previous inner observable whenever a new outer value arrives. Pairing it with firstValueFrom gives you the first value of the inner stream per outer event:
clicks$.pipe(
switchMap(() => interval(1000)),
firstValueFrom()
).subscribe(n => console.log(`click ${n}`));
Here each click triggers a fresh interval and returns its initial tick, rather than accumulating ticks for every click.
Complete Example Session
// ============================================
// PART 1: THE TITLE
// ============================================
import { firstValueFrom, lastValueFrom } from "rxjs";
import { of, Promise, fromEvent } from "rxjs";
import { switchMap } from "rxjs";
// Simple Observable extraction
const obsResult = of(1, 2, 3).pipe(firstValueFrom());
console.log(obsResult); // 1
// Promise extraction
const promResult = Promise.resolve(42).pipe(firstValueFrom());
console.log(promResult); // 42
// ============================================
// PART 2: FIRST VALUE FROM A PROMISE ONLY
// ============================================
const onlyPromise = Promise.resolve({ id: 7 }).pipe(firstValueFrom());
console.log(onlyPromise); // { id: 7 }
// ============================================
// PART 3: LAST VALUE FROM AN OBSERVABLE
// ============================================
const lastObs = of(10, 20, 30).pipe(lastValueFrom());
console.log(lastObs); // 30
// ============================================
// PART 4: COMBINED PIPE WITH SWITCHMAP
// ============================================
const clicks$ = fromEvent(document, "click");
const switchedFirst = clicks$.pipe(
switchMap(() => interval(500)),
firstValueFrom()
);
switchedFirst.subscribe(n => console.log(`tick after ${n}`: n));
// ============================================
// PART 5: ERROR HANDLING
// ============================================
const failing$ = of(1, 2, Promise.reject(new Error("boom"))).pipe(firstValueFrom());
failing$.subscribe({
next: (v) => console.log("next:", v),
error: (e) => console.log("error:", e.message)
});
// ============================================
// PART 6: CANCELATION VIA ABORT SIGNAL
// ============================================
const controller = new AbortController();
longRunning$
.pipe(
// Turn the signal into a notifier observable
takeUntil(fromEvent(controller.signal, "abort"))
)
.subscribe(value => console.log("value:", value));
controller.abort(); // triggers cleanup
// ============================================
// PART 7: FINAL VALUE WITH LASTVALUFFROM
// ============================================
const counter$ = fromEvent(window, "resize").pipe(
lastValueFrom()
);
counter$.subscribe(count => console.log("last resize count:", count));
// ============================================
// PART 8: SHARE REPLAY WITH REF COUNT TRUE
// ============================================
const source$ = of(1, 2, 3).pipe(shareReplay({ bufferSize: 1, refCount: true }));
source$.subscribe(nextVal => console.log("shared next:", nextVal));
// ============================================
// PART 9: FINALIZE FOR RESOURCE CLEANUP
// ============================================
const socket = new WebSocket("wss://example.com/feed");
socket$.pipe(finalize(() => socket.close())).subscribe(msg => console.log("socket closed:", msg));
// ============================================
// PART 10: REAL-WORLD SCENARIO โ FORM INPUT CLICK HANDLER
// ============================================
const viewSub = new Subscription();
viewSub.add(fromEvent(document, "input").subscribe(e => {
const term = e.target.value;
// Extract first numeric value from the term
const firstNum = Number(firstValueFrom(Promise.resolve(term)));
console.log(`processed term "${term}" โ first num: ${firstNum}`);
}));
viewSub.unsubscribe();
The ten parts moved from the leak itself through each of the four cancellation mechanisms: the notifier, the notifier’s own lifecycle, the resource hook in finalize, the Subscription container with its closed guard, the operators that already own their inners, both directions of the AbortSignal bridge, and finally the retention cases where a subscription is meant to stay open.
Quick Reference
The Four Cancellation Tools
| Tool | What It Ends | How It Ends |
|---|---|---|
takeUntil(notifier$) | The chain above it | Completion |
Subscription.unsubscribe() | The container and all children | Teardown cascade |
AbortSignal / abortable | The source and platform resource | AbortError |
switchMap / take(1) | The inner or the source | Operator-managed |
takeUntil Rules
| Rule | Reason |
|---|---|
| Place it last in the pipe | Nothing downstream can resubscribe the source |
Use a shared Subject | A per-subscription notifier is never emitted into |
| Emit, then complete the notifier | Emission stops streams, completion releases the Subject |
Never pass EMPTY | Completion without emission never fires |
Subscription API
| Member | Behaviour |
|---|---|
add(teardown) | Attaches a child; returns void in RxJS 7 |
remove(teardown) | Detaches without unsubscribing |
unsubscribe() | Cascades to all children, in order |
closed | true after unsubscribe; add then runs immediately |
unsubscribe twice | Safe no-op |
Leak-Prone Operators
| Operator | Risk |
|---|---|
mergeMap | Keeps every inner subscription open |
shareReplay({refCount:false}) | Keeps the source open with no subscribers |
retry() / repeat() | Resubscribes without a bound |
Subject | Holds every subscriber until they unsubscribe |
Best Practices
โ Do This:
// Give every indefinite stream an explicit owner
interval(1000).pipe(takeUntil(destroy$)).subscribe(); // โ
// Keep takeUntil as the last operator in the pipe
source$.pipe(switchMap(fetchItem), takeUntil(destroy$)); // โ
// Aggregate related streams into one Subscription
const root = new Subscription().add(a$).add(b$); // โ
// Release platform resources in finalize
socket$.pipe(finalize(() => socket.close())); // โ
// Pass the signal through to fetch
fromFetch(url, { signal: controller.signal }); // โ
// Tie a replay cache to its subscriber count
source$.pipe(shareReplay({ bufferSize: 1, refCount: true })); // โ
โ Don’t Do This:
// Subscribe to an indefinite source and walk away
interval(1000).subscribe(render); // โ
// Put a resubscribing operator below takeUntil
source$.pipe(takeUntil(destroy$), repeat()); // โ
// Use a fresh Subject per subscription as the notifier
source$.pipe(takeUntil(new Subject<void>())); // โ
// Rely on unsubscribe alone to close a socket or request
socket$.subscribe(handle); // โ
// Keep a cache warm without meaning to
source$.pipe(shareReplay({ refCount: false })); // โ
// Use unbounded retry on a failing source
request$.pipe(retry()); // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Handler fires many times | Each mount subscribed again, none unsubscribed | takeUntil per lifecycle |
takeUntil never fires | Notifier completes without emitting | Emit before complete() |
| Notifier does nothing | A new Subject created per subscription | Share one Subject |
| Chain restarts forever | repeat/retry placed below takeUntil | Move takeUntil last |
| Request survives teardown | No signal passed to fetch | fromFetch or signal |
| Cache never releases | shareReplay({ refCount: false }) | refCount: true |
| Duplicate inner timers | mergeMap over a non-completing inner | switchMap or exhaustMap |
| Teardown does not run | Cleanup in complete instead of finalize | Use finalize |
Real-World Examples
1. Page-scoped destroy notifier
const destroy$ = new Subject<void>();
interval(1000).pipe(takeUntil(destroy$)).subscribe(render);
destroy$.next(); destroy$.complete();
2. Notifier from a DOM signal
const controller = new AbortController();
stream$.pipe(takeUntil(fromEvent(controller.signal, "abort"))).subscribe();
3. One container per view
const viewSub = new Subscription().add(a$.subscribe(h)).add(b$.subscribe(g));
viewSub.unsubscribe();
4. Releasing a socket in finalize
socket$.pipe(finalize(() => socket.close())).subscribe(handle);
5. Cancelling the previous request
input$.pipe(switchMap((t) => fromFetch(`/api?q=${t}`))).subscribe();
6. Detecting a mergeMap leak
// One permanent interval per click โ unbounded growth
clicks$.pipe(mergeMap(() => interval(1000))).subscribe();
7. Aborting an observable with a signal
interval(1000).pipe(abortable(controller.signal)).subscribe({ error: ignoreAbort });
8. Wiring a signal into fetch
fromFetch("/api/data", { signal: controller.signal }).pipe(switchMap((r) => r.json()));
9. A self-expiring request timeout
fromFetch("/api/slow", { signal: AbortSignal.timeout(5000) });
10. Bounding a replay cache
state$.pipe(shareReplay({ bufferSize: 1, refCount: true }));
Visual
The Dangling Subscription
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE LEAK โ
โ โ
โ subscribe() โโโบ Subscriber โโโบ observer list โ
โ โ
โ interval(1000) emits forever โ
โ nothing removes the entry unless you cancel โ
โ โ
โ unsubscribe() โโโบ entry removed โ
โ complete โโโบ entry removed โ
โ neither โโโบ entry stays โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
takeUntil Completes the Chain
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ takeUntil: COMPLETION, NOT UNSUBSCRIBE โ
โ โ
โ notify$.next() โ
โ โ โ
โ โผ โ
โ source$ โโโบ takeUntil(notify$) โโโบ subscriber โ
โ โ โ
โ โโโโบ source completes โ
โ โโโโบ complete propagates โ
โ โโโโบ Subscription closed โ
โ โโโโบ teardowns run โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Subscription Container
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE SUBSCRIPTION TREE โ
โ โ
โ root = new Subscription() โ
โ โโโ add(a$.subscribe()) โ teardown A โ
โ โโโ add(b$.subscribe()) โ teardown B โ
โ โโโ add(c$.subscribe()) โ teardown C โ
โ โ
โ root.unsubscribe() โ
โ โโโโบ A, B, C torn down โ
โ โ
โ root.closed === true โ
โ โโโโบ add() runs immediately after this โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Two AbortSignal Bridges
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ TWO BRIDGES โ
โ โ
โ SIGNAL โ OBSERVABLE โ
โ signal โโโบ fromEvent(signal, 'abort') โโโบ takeUntil โ
โ โ
โ OBSERVABLE โ SIGNAL โ
โ signal โโโบ abortable(signal) โโโบ source$ โ
โ controller.abort() โโโบ unsubscribe + AbortError โ
โ โ
โ fromFetch(url, { signal }) wires both ends for you โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| What leaks | The Subscriber and the closure it holds |
| Default lifetime | Until unsubscribe or source completion |
| General notifier | takeUntil(notifier$) |
| Notifier shape | A shared Subject<void> |
| Notifier position | Last operator in the pipe |
| Container | Subscription with add() children |
| Resource hook | finalize() โ complete, error AND unsubscribe |
| Signal โ stream | `from |
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!