FreshMvvm
FreshMvvm copied to clipboard
Asyncronous operations inside Init method
In this method I want to call to an asynchronous method to retrieve some data from server, but I see that this method is a void.
So, what is the recommended way to use the "await" operator here? Am I using the correct method?
I mean, I want to be sure that the usage of the Init method what I am doing is the correct one, or if for example the correct method for this purpose is ViewIsAppearing.
Thanks.
Did you find a good way to do this? Currently I'm just prefixing the Init method with async like so:
public override async void Init(object initData)
{
await AsyncMethod();
}
I'm also in the same boat and don't know if this is the best way to do it.
With async void, no one will wait for it to finish, as it's a "fire-and-forget" way of doing things. Therefor it might not be finished when the view is loaded. You can try putting a "await Task.Delay" before the AsyncMethod and see if this is what you actually want.
To get something similar to a "Task Init", I would probably done the async job before PushPage, and then put a parameter with the result in the init method.
The problem with implementing a Task return type, it must actually return something. Therefor there will therefor be some unnecessary overhead.
However there might be some ways of implementing something like this, because the PushPageModel is itself async. Today the "Init" happens in the last method (BindingPageModel) of: https://github.com/rid00z/FreshMvvm/blob/master/src/FreshMvvm/FreshPageModelResolver.cs
I guess one way to implement this, could be a interface on the model (or a different baseclass), with a Task Init method you can override. Then check this before calling the BindingPageModel method, and instead calling a similar method that support async.
The result will then be the same. No page is opened before the init is completed.
await Init(data);
This could indeed result in the page load occurring before the data is initialized.
@oddbear has a good suggestion: "To get something similar to a "Task Init", I would probably done the async job before PushPage, and then put a parameter with the result in the init method."
Option 2 edit Thanks @oddbear Updated to remove the deadlock, previously Init was blocking the context thread, waiting for MethodAsync to complete, and MethodAsync was waiting for the context to be free so it could complete.
You'll need to show a loading indicator on the screen while MethodAsync does its work, but this is definitely a better approach.
// Non-blocking
public void Init(object initData)
{
MethodAsync(initData).ContinueWith((tResult) => {
// Process fault
}, TaskContinuationOptions.OnlyOnFaulted);
}
// Just a sample async method.
public async Task MethodAsync(object initData)
{
await Task.Run(() => {
this.SomeMember = initData.ToString();
});
}
We've discussed this before, over here: https://github.com/rid00z/FreshMvvm/issues/24
It seems to get a few people, this work below but I'm wondering if I should actually make the init a Task.
public override void Init (object initData)
{
LongRunningTask ().RunForget ();
}
async Task LongRunningTask()
{
//show loading screen
await Task.Delay (5000);
Contacts = new ObservableCollection<Contact> (_databaseService.GetContacts ());
//stop loading screen
}
There's also this.
public static void RunForget(this Task t)
{
t.ContinueWith((tResult) =>
{
//Console.WriteLine(t.Exception)
//TODO: Log to Xamarin insights
},
TaskContinuationOptions.OnlyOnFaulted);
}
@C0D3Name that code will cause a deadlock for 5 seconds in most cases, if executed on the UI thread (depends on the SynchronizationContext).
@rid00z that code is really nice, and probably solves most problems. I would guess this is the most preferred way for the user to see some loading.
The big question is if the developer (and the user), want: Scenario A: a loading indicator on the current page, and then immediately open up a new page when it's done. Scenario B: open up a new page, with a loading indicator/spinner.
Your code would solve the B scenario. Making the init a Task, could help (but probably most confuse) in the A scenario.
//The A scenario, should be the same result as "Task Init":
public async Task LoadSomePage()
{
//Loading logic:
var result = await SomeAsyncMethod();
await CoreMethods.PushPageModel<ModelName>(result);
//Stop loading logic!
}
A possibility can also be to have both a "Task Init" and "void Init", where the developer can override and use one, or both of them.
My code sets the result of the Async method to a new ObservableCollection as in LongRunningTask
. But I now see no items in my UI since adding RunForget(), even though the ObservableCollection has a valid item in it. Has anyone seen any behaviour like this before?