Pages

Monday, June 24, 2019

Loading async data in the constructor of the view model in Xamarin

Whenever I have a page that loads data once constructed I start to baffle about how to do the async work in the constructor? I posted a question on Stackoverflow to know how other fellows cope with this dilemma, one commented that I can create an event for that and fire it in the constructor, the event handler can be async, so problem solved- in an ugly workaround, I mean, really! create event to call other method in the same class? don't blame async!

Until I watched this Channel9 episode , the guest (Brandon Minnick) suggested a nice workaround, that fits closely to the MVVM pattern:
Create a command that loads the data in its execute function (that can be async), and in constructor of the view model, we can just do LoadCommand.Execute(null); //done.

and this is really nice solution, I see commands as the MVVM's capsules of data, so putting some work in them is very reasonable, off course if the work isn't async there's no point encapsulating it in a command unless you want to share the same work between views.. but using them to be able to run async from constructor is not costly/ ugly solution.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

How to do code reviews correctly

Introduction Code review is a special event in the life cycle of software development, it's where ownership is transferred from the deve...