Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat async task by timer in xamarin forms

i'm new to xamarin.forms development and i'm still having my first steps from the few tutorials that are found on the net. I have an async task that returns the time from date.jsontest.com and i have a timer that decrements a text in a label. i want to put the async task in the timer so that it repeats itself and displays the time on the label however im getting cannot convert async lamba to func

here's my code please help me, thanks

static async Task<string> RequestTimeAsync()
    {
        using (var client = new HttpClient())
        {
            var jsonString = await client.GetStringAsync("http://date.jsontest.com/");
            var jsonObject = JObject.Parse(jsonString);
            return jsonObject["time"].Value<string>();
        }
    }


 protected override async void OnAppearing()
    {
        base.OnAppearing();

        timeLabel.Text = await RequestTimeAsync();

        Device.StartTimer(TimeSpan.FromSeconds(1), () => { // i want the taks to be put 
//here so that it gets repeated
            var number = float.Parse(button.Text) - 1;
            button.Text = number.ToString();
            return number > 0;
        });

    }

Reloading the Content Page in the timer would do the trick, so if anybody can please help me it would be appreciated

like image 706
eshteghel company Avatar asked Aug 08 '16 09:08

eshteghel company


Video Answer


1 Answers

You just need to wrap the async method call in a Task.Run(), for example:

Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
  Task.Run(async () =>
  {
    var time = await RequestTimeAsync();
    // do something with time...
  });
  return true;
});
like image 73
Michael Landes Avatar answered Oct 25 '22 06:10

Michael Landes