Skip to content

[API Proposal]: ConcatWhenEach for IAsyncEnumerable<T> #112165

@WhatzGames

Description

@WhatzGames

Background and motivation

Concatenating asynchronous data is currently only returned in the order in which the AsyncEnumerables are passed into Concat.
In the case that the order of the data itself does not matter, having to wait for a previous sequence to fully complete is not necessary.

E.g. collecting data through separate paginated sources like an API and a database would require for one of the two to wait for the previous stream to be completely read. (This might not be the best example, but I hope you get the idea.)

The goal of this proposal is to take the idea of Task.WhenEach() and instead of waiting for a full completion of the first sequence, it would be possible to iterate over the results as soon as one of the two sequences returns a new entry.

API Proposal

namespace System.Linq;

public static class AsyncEnumerable
{
    public static IAsyncEnumerable<T> ConcatWhenEach(this IAsyncEnumerable<T> source, IAsyncEnumerable<T> other);
    //This one is optional. As Task.WhenEach would provide an IAsyncEnumerable<T> already
    public static IAsyncEnumerable<T> ConcatWhenEach(this IAsyncEnumerable<T> source, IEnumerable<Task<T>> other);
}

API Usage

// return entries with ~3 ms delay per entry
IAsyncEnumerable<Data> source = GetDataFromAPI();
// return entries with ~1ms delay per entry 
IAsyncEnumerable<Data> other = GetDataFromDatabase();

// returns other[0], other[1], source[0], other[2], other[3], other[4], source[1], other[5] etc... 
source.ConcatWhenEach(second)

Alternative Designs

Currently I can't think of any other approach, but I'm open to any other possible suggestions and discussions.

Risks

None that come to mind.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Linq

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions