Can I overload a template async function without it executing when associated?

Jesse Knott 686 Reputation points
2021-05-03T19:24:18.947+00:00

I have a series of functions that I use as a base for my ViewModels. These get overloaded in each class that uses the baseviewmodel.cs.

Here's an example.

BaseViewModel.cs

    ....

    public Task InitBase { get; internal set; }
    public Task Initialization { get; internal set; }
    public Task InitInventory { get; internal set; }

    ....

InventoryPageViewModel.cs

public InventoryPageViewModel : BaseViewModel

public InventoryPageViewModel()
{
  InitBase  = CustomInitializationFunc(); //This code executes the CustomInitializationFunc

}

public async Task CustomInitializationFunc()
{
  ... some initialization class ...
}
        

The problem I have is this. When the InitBase is assigned, it is running the code in the function being assigned. The function has code that can only be executed after the page has been loaded, I can add code to prevent the function from running unless a flag is set for the page being ready. However It would be easier to be able to run the initialization without having to execute the function as it's being assigned. Later in the code I will use await InitBase; to execute the function, but

I hope this makes sense.

Cheers!

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

Accepted answer
  1. JessieZhang-MSFT 7,706 Reputation points Microsoft Vendor
    2021-05-04T03:03:47.747+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    The problem I have is this. When the InitBase is assigned, it is running the code in the function being assigned. The function has code that can only be executed after the page has been loaded, I can add code to prevent the function from running unless a flag is set for the page being ready.

    When you set the BindingContext for your page,once the page been created, the constructor of your ViewModel will been called at the same time.

    If you want some code in the constructor of your ViewModel willn't been executed , you can set some condition(e.g. a bool flag) just as you mentioned.

    In addition, you can also add your code in function OnAppearing by override function OnAppearing:

        protected override void OnAppearing()  
        {  
            base.OnAppearing();  
            // add your code here  
        }  
    

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful