I was pleasantly surprised to learn that this works as a streamable response in ASP.NET:
MapGet("/", GetStream);
private static Wrapper GetStream()
{
var stream = CreateStream();
return new Wrapper
{
Data = stream,
Cursor = ""
};
}
private static async IAsyncEnumerable<int> CreateStream()
{
for (var i = 0; i < 5; i += 1)
{
yield return i;
await Task.Delay(1000);
}
}
class Wrapper
{
public IAsyncEnumerable<int> Data { get; set; }
public string Cursor { get; set; }
}
i.e. if you request this, the response will be streamed in parts, e.g.: { "data": [0, 1, 2
until it finally completes, e.g. { "data": [0, 1, 2, 3, 4], "cursor": "" }
However, is there a way to defer the population of one of these properties - in this case my Cursor
property - until the stream has completed? For example, in this case I'd want to set the cursor to the something calculated from the final data item that was emitted.