问题
I have some async calls from Init in view model. The problem is that sometimes async call returns before OnCreate, and the property in UI is not updated. Is there proper async/await model for this case, when we have to init async data?
pseudo code:
// ViewModel
public async Task Init(string id)
{
Url = await LoadUrlAsync(id);
}
// View
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.ui_xml);
ViewModel.PropertyChanged += ViewModel_PropertyChanged;
}
void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
_webView.LoadUrl(ViewModel.Url);
}
回答1:
I'd probably do something like this in the OnCreate method, as you might want to add additional properties to it in the future.
private bool _loaded;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.ui_xml);
ViewModel.WeakSubscribe(() => ViewModel.Url, (s,e) =>
{
if (!_loaded)
_webView.LoadUrl(ViewModel.Url);
});
if (ViewModel.Url != null) //Check if the async Init has finished already
{
_webView.LoadUrl(ViewModel.Url);
_loaded = true;
}
}
来源:https://stackoverflow.com/questions/19408287/async-init-and-property-changed-in-mvvmcross