How to wait for an async function to finish an async function

Carlos A. López 1 Reputation point
2022-02-07T14:05:22.89+00:00

Hello, experts:

Maybe this was answered before, but I can't find an answer to this case.
I have an app. I made a tabbed page, with two pages and a ViewModel. In that ViewModel I have two lists, pending and selected. Every list shows on his own tab. Ok.

When I click on a line in the pending list, I call a command that calls:

await SendToSelected(item).

This function calls a ModalPage to select the ammount of items of different colors, and then, create an element for every color I choosed.

[code]
    MessagingCenter.Subscribe<MyItemsViewModel, ObservableCollection<SelectedColorModel>>(this, myMessageSubscription,
                                    (sender, data) =>
                                    {
         //do some stuff and create a copy on selected list
         MessagingCenter.Unsubscribe<MyItemsViewModel, ObservableCollection<SelectedColorModel>>(this, myMessageSubscription);
                                    });


                    await Navigation.PushModalAsync(new SelectColorsPage()
                    {
                        BindingContext = new SelectColorsViewModel(pendingLine, myMessageSubscription,)
                                        { Navigation = this.Navigation },
                        Title = TextResources.SelectColor + ": " + pendingLine.description
                    });
[/code]

Ok, it work perfect, as usual: open the new page, select colors, return a list, create data... Cool!

Now I need to create a button on pending page to add all the items, but I still need to choose the quantity of every color of every item. No problem, just make a loop and call this function with an await:

[code]
for (int i = pendingList.Count - 1; i >= 0; i--)
                    await ExecuteMoveItemFromPendingToSelectedAsync(pendingList[i]);
[/code]

The problem is that this loop open the modal page several times, it doesn't wait until ModalPage is closed, and if I click on the OK button on that page, it sends the info of all modalPages, even if I only was able to modify the latest one.
I had this problem every time an async function calls an async method, the parent doesn't wait until chil has finished or returned a value (usually, some info from WebAPi) and get a lot of empty lists, even if they're loaded from my WebApi.

The only answer I found was "copy the async part of the child on the parent", but that is repeating code, and I don't think it's a good solution.
So, can someone tell me how to wait an async funtion to await an async function on its child?

Thank you.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,326 questions
{count} votes