Skip to content

Proposal: Add flatMapLatest operator #381

@peterfriese

Description

@peterfriese

I would like to propose adding a flatMapLatest operator to AsyncSequence.

Motivation

When transforming elements of an asynchronous sequence into new asynchronous sequences, there are cases where only the results from the most recent transformation are relevant. A common example is a search-as-you-type interface where each keystroke triggers a network request. If a new request starts, the previous one becomes irrelevant and should be cancelled to save resources and avoid displaying stale data.

Proposed Solution

Add a flatMapLatest operator that transforms each element from the base AsyncSequence into a new inner AsyncSequence. When a new element is produced by the base sequence, iteration on the current inner sequence is cancelled, and iteration begins on the newly created sequence.

Example

let searchResults = searchQueries.flatMapLatest { query in
  searchAPI(query)
}

for await result in searchResults {
  displayResults(result) // Only latest results displayed
}

I've prepared an Evolution proposal and a prototype implementation including tests (see https://github.com/peterfriese/swift-async-algorithms/tree/flatMapLatest/statemachine)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions