Created
April 6, 2025 08:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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