Coalesce pending asynchronous tasks

Hi! I have an asynchronous task that performs expensive operations. I have the following requirements:

  • There must be at most one of these tasks running at a time.
  • Pending tasks may be added multiple times while a running task is still executing.
  • Pending tasks should be coalesced into a single pending task, merging the requests into a single request.

Is it possible to model this using the existing AsyncSequence algorithms? If not, what new algorithms would we need to introduce in order to satisfy these requirements?

Maybe an AsyncBufferSequence with a new AsyncBufferSequencePolicy that supports coalescing?

let pendingRequests = requests.buffer(policy: .coalescing({ (existing, new) in
  return merge(existing, new)
}))

Or just a new AsyncCoalescingSequence? :thinking:

let pendingRequests = requests.coalesced { (existing, new) in
  return merge(existing, new)
}