1

I'm struggling with the mix of sync. and async calls in language-ext.

I've the following simplified example:

void Main()
{
    var content = 
    Validate("https://www.google.com")
    .Bind(Transform)
    .Bind(FetchUriAsync);
}

private static Either<Error, string> Validate(string url)
{
    return url;
}


private static Either<Error, Uri> Transform(string uri)
{
    var uriBuilder = new UriBuilder(uri);
    return uriBuilder.Uri;
}

private static async EitherAsync<Error,HttpContent> FetchUriAsync (Uri uri)
{
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync(uri);
    
    return response.Content;
}

How can I bind FetchUriAsync to the previous calls?

Thx

Moerwald
  • 10,448
  • 9
  • 43
  • 83

1 Answers1

1

Assuming you want content to be an EitherAsync<Error, HttpContent>, you can use ToAsync to convert the Either to an EitherAsync, and then you can Bind.

var content = 
    Validate("https://www.google.com")
    .Bind(Transform)
    .ToAsync()
    .Bind(FetchUriAsync);

Also, your current implementation of FetchUriAsync doesn't compile, since async methods can't return EitherAsync. I assume you meant something like this:

private static EitherAsync<Error, HttpContent> FetchUriAsync(Uri uri) => 
    TryAsync(async () =>
        (await new HttpClient().GetAsync(uri)).Content
    ).ToEither();
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Thx for your answer. Actually I'm struggling a bit with language-ext. Can you recommend some learning-sources? – Moerwald Jun 09 '23 at 17:17