1

I have a question. My activity Indicator dismisses before my images are finished loading from my api. Is it because the call to the api is async? If so, how can I make sure the call is done or the images are loaded on the screen before dismissing my activity indicator?

The activity indicator code in my XAML looks like this:

  <ActivityIndicator IsRunning="{Binding IsBusy}"
                             IsVisible="{Binding IsBusy}"
                             VerticalOptions="Center"
                             HorizontalOptions="Center"/>

My property (which is located in viewmodel base):

private bool isBusy;
        public bool IsBusy
        {
            get { return isBusy; }
            set { SetProperty(ref isBusy, value); }
        }

And this is the code where I set the property:

  public override async void OnNavigatingTo(NavigationParameters navParams)
        {
            if(navParams.ContainsKey("query"))
            {
                var query = (string)navParams["query"];
                IsBusy = true;
                await DisplayImages(query);
                IsBusy = false;

            }
        }

Thanks!

Euridice01
  • 2,510
  • 11
  • 44
  • 76

2 Answers2

1

I'm not at my computer, and it's tricky to do on this device, but here goes...

Option 1: BackgroundWorker

Async/await doesn't make it run on a background thread, you need the loading to occur on a background thread. And be aware that Tasks and threads are different.

Create a field on your class, type BackgroundWorker. Hook up the DoWork event of that field to be a method containing:

            IsBusy = true;
            DisplayImages(query);
            IsBusy = false;

And where those lines used to be, call RunWorkerAsync on your field. You can put the value of query into a field so it can be used from the DoWork method.

Option 2: an actual thread

Put the 3 lines in a method called Load(string query). Where those lines used to be, do this:

myNewThread = new Thread(() => Load(query));
myNewThread.Start();

I think myNewThread needs to be a field so it doesn't get garbage collected.

Richardissimo
  • 5,596
  • 2
  • 18
  • 36
0

Implement in your method using:

Device.BeginInvokeOnMainThread(async () =>
{
   //load your images here
   //Lastly set IsBusy to false
});
Joakim M
  • 1,793
  • 2
  • 14
  • 29