Calling async method from ViewModel
<p>I have a <code>ViewModel</code>, which makes use of <a href="https://blog.xamarin.com/simplifying-events-with-commanding/" rel="nofollow noreferrer"><code>Commanding</code></a>. In this <code>ViewModel</code> I want to access the <a href="https://github.com/jamesmontemagno/MediaPlugin" rel="nofollow noreferrer">MediaPlugin
</a>. With this plugin I have to call <a href="https://github.com/jamesmontemagno/MediaPlugin/issues/61#issuecomment-243572982" rel="nofollow noreferrer"><code>Initialize()</code></a>. Because it uses <code>async</code> calls I have some timing problems.</p>

<p>This is my code:</p>

<pre><code>public ICommand CameraCommand
{
    get { return _cameraCommand ?? (_cameraCommand = new Command(async () =&gt; await ExecuteCameraCommand(), () =&gt; CanExecuteCameraCommand())); }
}

public bool CanExecuteCameraCommand()
{
    // Check if initialized before calling properties
    if (!this.initialized)
        InitMedia();

    if (!this.initialized || !CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
    {
        return false;
    }
    return true;
}

public async Task ExecuteCameraCommand()
{
    // Assure that it is initialized before calling method
    var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions {});
    // ...
}

private void InitMedia()
{
    CrossMedia.Current.Initialize();
    this.initialized = true;
}
</code></pre>

<p>With this code the app crashes with</p>

<blockquote>
  <p>You must call Initialize() before calling any properties.<br>
  at Plugin.Media.MediaImplementation.get_IsCameraAvailable()</p>
</blockquote>

<p>When I start the initialization in the constructor like with this code</p>

<pre><code>public MyViewModel()
{
    InitData();
}

private async Task InitData()
{
    // ...
    await InitMedia();
}

private async Task InitMedia()
{
    await CrossMedia.Current.Initialize();
    this.initialized = true;
}

public bool CanExecuteCameraCommand()
{
    // Check if initialized before calling properties
    if (!this.initialized)
        return false;
    // ...
}
</code></pre>

<p><code>CanExecuteCameraCommand()</code> is called before the initialization has finished. As a consequence <code>false</code> is returned and the button in the UI is disabled.</p>

<p>I'm testing this code in a Xamarin.Forms environment on a Windows 10 Mobile device (Windows 10 Universal).</p>