Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Matheos96/7119d2e4088be777d54c2cff8730db28 to your computer and use it in GitHub Desktop.
Save Matheos96/7119d2e4088be777d54c2cff8730db28 to your computer and use it in GitHub Desktop.
Simple extension method that performs a get request to the given endpoint and returns an IAsyncEnumerable<T?> which emits a value every time the server streams a new value
namespace blazorwasm;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Components.WebAssembly.Http;
public static class Extensions
{
public static IAsyncEnumerable<T?> GetFromJsonAsAsyncEnumerableUsingStreaming<T>(
this HttpClient client, string? uri, CancellationToken ct = default)
=> GetFromJsonAsAsyncEnumerableUsingStreaming<T>(client, string.IsNullOrEmpty(uri) ? null : new Uri(uri, UriKind.RelativeOrAbsolute), ct);
public static async IAsyncEnumerable<T?> GetFromJsonAsAsyncEnumerableUsingStreaming<T>(
this HttpClient client,
Uri? uri,
[EnumeratorCancellation] CancellationToken ct = default)
{
using var request = new HttpRequestMessage(HttpMethod.Get, uri);
request.SetBrowserResponseStreamingEnabled(true);
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
await foreach (var item in response.Content.ReadFromJsonAsAsyncEnumerable<T>(cancellationToken: ct))
yield return item;
}
}
public class MyClass
{
public async Task MyMethod()
{
try
{
await foreach (var item in Http.GetFromJsonAsAsyncEnumerableUsingStreaming<int>("api/someStream"))
{
// Do something with emitted item
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error streaming data: {ex}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment