Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Android F# update UI in async block

I'm new to Xamarin, and am trying to build a simple Android app with F#. I'm trying to load in data from a REST API with async, and then display it. I understand that interacting with the UI must be done on the MainThread, and that there is something along the lines of Activity.RunOnUiThread(). I've tried the following:

let onSearch args =
        let search = this.FindViewById<EditText>(Resource_Id.search)
        let searchResults = this.FindViewById<TextView>(Resource_Id.searchResults)

        button.Text <- search.Text
        async {
            let! results = recipeSearch.GetRecipes search.Text
            searchResults.Text <- results
        }
        |> Async.Start

    button.Click.Add onSearch

Which throws the Exception about interacting with the UI elements in another thread. And this:

    let result = async {
                    let! results = recipeSearch.GetRecipes search.Text
                    return results
                }
                |> Async.RunSynchronously
    searchResults.Text <- result

Defeats the purpose of doing it Async

Thanks

like image 544
kaeedo Avatar asked Jun 10 '16 21:06

kaeedo


People also ask

Does Xamarin support F#?

F# supports the development of Android and iOS applications using the Xamarin tools. Both native and cross-platform app development is possible. Install JetBrains Rider, or Visual Studio for Mac. Select F# Language support as part of installation.

Is Xamarin being discontinued?

Xamarin support will end on May 1, 2024 for all Xamarin SDKs. Android 13 and Xcode 14 SDKs (iOS and iPadOS 16, macOS 13) will be the final versions Xamarin will target.

Is Xamarin an Android?

Xamarin is an open-source platform for building modern and performant applications for iOS, Android, and Windows with . NET. Xamarin is an abstraction layer that manages communication of shared code with underlying platform code.

Is Xamarin deprecated Android?

Not dead but possibly moribund. In May 2020, Microsoft announced that Xamarin. Forms, a major component of its mobile app development framework, would be deprecated in November 2021 in favour of a new .


1 Answers

Try this:

let onSearch args =
        let search = this.FindViewById<EditText>(Resource_Id.search)
        let searchResults = this.FindViewById<TextView>(Resource_Id.searchResults)

        button.Text <- search.Text
        async {
            let! results = recipeSearch.GetRecipes search.Text
            this.RunOnUiThread(fun () -> searchResults.Text <- results)
        }
        |> Async.Start

    button.Click.Add onSearch
like image 92
jzeferino Avatar answered Oct 13 '22 18:10

jzeferino