asyncMap<S, T> static method
Maps each payload through an asynchronous mapper.
asyncMap processes pulses sequentially. If a new pulse arrives while a mapper is still running, it is queued until the previous one completes.
When to use
Use asyncMap when you need to perform I/O or heavy computation where order must be strictly preserved.
- Database Writes: Ensuring records are saved in order.
- API Requests: When the server requires sequential processing.
How it works
- Incoming pulses are added to an internal queue.
- The
mapperis called for the first item in the queue. - The instruction waits for the resulting Future to resolve.
- Once resolved, the next item in the queue is processed.
When to use
Use asyncMap when you need to perform async operations on each value and order matters.
- Network Requests: Making sequential API calls.
- Database Operations: Sequential database queries.
- File I/O: Reading/writing files sequentially.
- Data Enrichment: Enriching data with async sources.
- Image Processing: Processing images sequentially.
- Encryption/Decryption: Applying async crypto operations.
How it works
- Each incoming pulse triggers the
mapper. - The async operation is awaited.
- The result is emitted.
- Inputs are queued while processing.
- If
mapperthrows an error, it's reported and the instruction continues with the next input. - Each emitted value gets the step
'AsyncMap'for provenance.
Parameters:
source: The Source Cell. The cell providing the input values.mapper: Mapping Function. Called with each typed payload, returns aFutureOr<T>.onError: Error Handler. Optional callback for handling errors.
Type Parameters:
S: The type of the input payload.T: The type of the output payload.
Returns:
A FlowHandle that can be used to observe the mapped values.
Example
final ids = Cell.ingress<int>();
final handle = Flow.asyncMap<int, User>(
ids.cell,
mapper: (id) async => await api.getUser(id),
);
ids.emit(1); // -> User 1
ids.emit(2); // -> User 2 (after User 1 completes)
See Also:
- asyncMapConcurrent: For concurrent mapping.
- asyncMapLatest: For latest-only mapping.
Implementation
static FlowHandle asyncMap<S, T>(
Cell source, {
required FutureOr<T> Function(S value) mapper,
AsyncMapErrorHandler? onError,
}) {
return AsyncMap<S, T>(mapper, onError: onError).toHandle(source: source);
}