0

In a piece of code using language-ext library, I can perform an async action only when the Option<> intermediate result is actually filled:

async Task<Option<MyEntity>> FindEntityAsync(string entityId)
{
    Option<MyEntity> entityOpt = await GetEntityAsync(entityId);

    if (entityOpt.IsSome)
    {
        await DoSomethingAsync(entityOpt.First());
    }

    return entityOpt;
}

// Task<Option<MyEntity>> GetEntityAsync(string entityId) { ... }

// DoSomethingAsync could either be:
//   Task DoSomethingAsync(MyEntity entity) { ... }
// or:
//   Task<Unit> DoSomethingAsync(MyEntity entity)

I'm looking for a more idiomatic way (for such library) to achieve the same.

I tried the following but it does not work:

// look ma! No async/await here
Task<Option<MyEntity>> FindEntityAsync(string entityId)
{
    Task<Option<MyEntity>> result =

        from entity in GetEntityAsync(entityId)

        from _ in DoSomethingAsync(entity).Map(Some)

        select entity;

    return result;
}

I experienced some LanguageExt.ValueIsNoneException when the Option<> is None.

Ideally I'd like to user an IterXxx type of operator in order to traverse the wrapped Option<MyEntity> only when there is something:

Task<Option<MyEntity>> FindEntityAsync(string entityId)
{
    Task<Option<MyEntity>> result = GetEntityAsync(entityId);

    result.IterXxxx(async entity => await DoSomethingAsync(entity));

    return result;
}

but I cannot find any suitable signature working with an async action. Any hint?

superjos
  • 12,189
  • 6
  • 89
  • 134

1 Answers1

0

There is special type OptionAsync<T> for combining two monads - Option and Async. For more info please refer to github - https://github.com/louthy/language-ext/issues/206

y.tsalko
  • 1
  • 1