@epikodelabs/streamix / src/public-api / handoff
Function: handoff()
handoff<
T,R>(options):Operator<T,R>
Defined in: projects/libraries/streamix/src/lib/operators/handoff.ts:104
Keeps one live resource active and swaps it for the next one only after the replacement is ready.
Think of it as double buffering for resources: while source value b is being prepared, the resource built for a stays active and in use. When b passes ready, it is emitted and the resource for a is disposed. If a newer value arrives before a provisional resource is ready, that work is aborted through its signal and the half-built resource is disposed without ever being emitted — latest wins.
The source is the stream passed to pipe; handoff is the operator applied to it. Source values are not retained: each value is handed to prepare, and only prepared resources are kept — the active one plus any replacement still being prepared.
Lifecycle of one source value:
prepare(value, signal)builds the replacement; the current resource stays active.ready(resource, signal)validates it.- The resource is emitted downstream and becomes active.
- The resource it replaced is disposed.
source a ───────── b ───────── c ────────►
prepare ├─ a ├─ b ├─ c
ready │ ✓ a │ ✓ b │ ✓ c
emit │ a │ b │ c
dispose │ │ a │ bA rejection from prepare or ready fails the output only while its value is still the latest; stale failures are ignored. The output completes after the source ends and the final replacement settles, disposing the active resource at the end.
Typical scenarios:
- Swapping the displayed image or video without blanking the screen while the next one loads.
- Replacing a connection, worker, or route view only after the replacement is ready, keeping the old one live until then.
- Cancelling stale preparations when the user changes selection quickly.
Use switchMap instead when each source value expands into a stream of values rather than one disposable resource.
Type Parameters
T
T
The type of values emitted by the source stream.
R
R
The type of the prepared resource emitted downstream.
Parameters
options
HandoffOptions<T, R>
Preparation, readiness, and disposal hooks.
Returns
Operator<T, R>
An operator that emits the latest resource that passed ready.
Example
// `selectedUrl` is the source stream of values to hand off from.
const selectedUrl = atom('/image-a.png');
const displayed = pipe(selectedUrl, handoff({
prepare: (url, signal) => loadImage(url, signal),
ready: (image) => image.decode(),
dispose: (image) => image.close(),
}));
// The old image stays on screen until the new one is decoded.
selectedUrl.set('/image-b.png');