The flatMapLatest operator transforms elements from an asynchronous sequence into new asynchronous sequences, but it only emits elements from the most recent inner sequence. When a new element arrives from the base sequence, any ongoing iteration on the previous inner sequence is immediately cancelled, and iteration begins on the new sequence.
This is ideal for scenarios where only the latest data matters, such as search-as-you-type, location updates, or dynamic configuration changes.
let searchQuery = AsyncStream<String> { continuation in
// User types into search field
continuation.yield("swi")
try? await Task.sleep(for: .milliseconds(100))
continuation.yield("swift")
try? await Task.sleep(for: .milliseconds(100))
continuation.yield("swift async")
continuation.finish()
}
let searchResults = searchQuery.flatMapLatest { query in
performSearch(query) // Returns AsyncSequence<SearchResult>
}
for try await result in searchResults {
print(result) // Only shows results from "swift async"
}