| | |

RxJS 13 ๐ŸŸฃ Promise & Async/Await Interop โ€” Bridging Observables and Promises

โฑ๏ธ Estimated read: 10 min | |

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

ToolWhat It EndsHow It Ends
takeUntil(notifier$)The chain above itCompletion
Subscription.unsubscribe()The container and all childrenTeardown cascade
AbortSignal / abortableThe source and platform resourceAbortError
switchMap / take(1)The inner or the sourceOperator-managed

takeUntil Rules

RuleReason
Place it last in the pipeNothing downstream can resubscribe the source
Use a shared SubjectA per-subscription notifier is never emitted into
Emit, then complete the notifierEmission stops streams, completion releases the Subject
Never pass EMPTYCompletion without emission never fires

Subscription API

MemberBehaviour
add(teardown)Attaches a child; returns void in RxJS 7
remove(teardown)Detaches without unsubscribing
unsubscribe()Cascades to all children, in order
closedtrue after unsubscribe; add then runs immediately
unsubscribe twiceSafe no-op

Leak-Prone Operators

OperatorRisk
mergeMapKeeps every inner subscription open
shareReplay({refCount:false})Keeps the source open with no subscribers
retry() / repeat()Resubscribes without a bound
SubjectHolds 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

PitfallWhy It HappensFix
Handler fires many timesEach mount subscribed again, none unsubscribedtakeUntil per lifecycle
takeUntil never firesNotifier completes without emittingEmit before complete()
Notifier does nothingA new Subject created per subscriptionShare one Subject
Chain restarts foreverrepeat/retry placed below takeUntilMove takeUntil last
Request survives teardownNo signal passed to fetchfromFetch or signal
Cache never releasesshareReplay({ refCount: false })refCount: true
Duplicate inner timersmergeMap over a non-completing innerswitchMap or exhaustMap
Teardown does not runCleanup in complete instead of finalizeUse 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

ItemValue
What leaksThe Subscriber and the closure it holds
Default lifetimeUntil unsubscribe or source completion
General notifiertakeUntil(notifier$)
Notifier shapeA shared Subject<void>
Notifier positionLast operator in the pipe
ContainerSubscription with add() children
Resource hookfinalize() โ€” complete, error AND unsubscribe
Signal โ†’ stream`from

Was this helpful?


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!