dotnet-websharper / ui

A reactive UI library for WebSharper.
https://websharper-samples.github.io/ui/
Apache License 2.0
77 stars 22 forks source link

Add async shorthands #283

Open granicz opened 6 months ago

granicz commented 6 months ago

I propose to add the following shorthands to make working with reactive vars/views easier (which are best handled asynchronously, instead of reading their values directly):

1) Var.GetAsync, as a counterpart to View.GetAsync:

```fsharp
type Var<'T> with
    member this.GetAsync =
        this.View |> View.GetAsync
```

2) Allowing Var<'T> and View<'T> to participate in async let! expressions:

```fsharp
[<AutoOpen;JavaScript>]
module Extensions =
    type AsyncBuilder with
        member this.Bind(var: Var<'T>, continuation: 'T -> Async<'U>) : Async<'U> =
            var.View |> View.GetAsync |> fun res -> async.Bind(res, continuation)
        member this.Bind(view: View<'T>, continuation: 'T -> Async<'U>) : Async<'U> =
            view |> View.GetAsync |> fun res -> async.Bind(res, continuation)
```

The latter would be especially useful, and would allow the following:

MainTemplate.ContactForm()
    .OnSend(fun e ->
        async {
            // Instead of reading e.Vars.Name.View |> View.GetAsync,
            // a much nicer way would be:
            let! name = e.Vars.Name
            // ... and same shorthand for views:
            let! email = e.Vars.Email.View
...