-
Notifications
You must be signed in to change notification settings - Fork 188
Description
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)