0

I am playing around with OneOf (https://github.com/mcintyre321/OneOf) nuget package, but I was wondering can I use it with IAsyncEnumerable operations so I camu up sith this little monster:

private async Task<OneOf<IAsyncEnumerable<string>, TypeNotFoundException>> AsyncTry()
{
    async Task<string> GetMessage(int n)
    {
        await Task.Delay(1000);
        return $"Message #{n}";
    }
    
    async IAsyncEnumerable<string> GetMessages(int max)
    {
        for (var i = 1; i <= max; i++)
        {
            var message = await GetMessage(i);
            yield return message;
        }
    }

    IAsyncEnumerable<string> enumerable = GetMessages(30);

    await foreach (var message in enumerable)
    {
        yield return message;
    }
    return new TypeNotFoundException("Undefined response type");
}

Problem is it does not accept it, so is this can be done?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Wojciech Szabowicz
  • 3,646
  • 5
  • 43
  • 87
  • 1
    What are you trying to do? If you want async streaming you have to return an `IAsyncEnumerable`, not `Task`. Just like `IEnumerable` that's the iteration interface, not the actual container, and can easily represent an empty stream. If your method returns without yield, the stream will be empty – Panagiotis Kanavos Aug 25 '23 at 10:02
  • You should really reconsider the logic of this method. If you intended to emulate a `Result` you could use `OneOf, SomeAppropriateError>` BUT an IAsyncEnumerable stream can be infinite. Even with an item limit, the actual calls may take a long time to complete. Whynot just return an `IAsyncEnumerable<>`? – Panagiotis Kanavos Aug 25 '23 at 10:13
  • 1
    As it is, even if you work out the syntax, your code will have to wait for `max` invocations before it returns that nothing was found. What would make sense is `IAsyncEnumerable>` to handle failed calls. – Panagiotis Kanavos Aug 25 '23 at 10:15

0 Answers0