Reputation: 1985
What is the best place to call a service and load data in xamarin forms
Till now I am calling the service in the view model constructor and loading data
I have a new situation - In my app I check for network connectivity, if it's not connected to internet I will not load data in the main form and show a modal form saying network is not available check. If the recheck is success will pop the modal but as the data is not loaded the main form is empty.
So in this case I have to write service call in on appearing override function. Which gets called after the modal popped. Which is okay. But problem is every time when we navigate to that view it will make a service call.
Please guide me the best place to call these services
Upvotes: 3
Views: 1238
Reputation: 89315
"...But problem is every time when we navigate to that view it will make a service call."
Create a flag (a boolean property), say IsLoaded
in the viewmodel (or view, depending on your current implementation), that set to false
initially. Then add a logic that check IsLoaded
flag before calling the service. If IsLoaded
is false
, run your current logic of checking internet connection, calling service, so on.. and lastly update IsLoaded
to true
.
Upvotes: 0
Reputation: 773
For your problem, you can use C# Events (Publisher-Subscriber) as the solution Write a event called InternetDisconnectedEvent in the View Model. Subscribe to that event in Code behind of the View (.xaml.cs)
Make UI Changes in the View, when internet disconnected.
For more about Event & Delegates, check this tutorial
Upvotes: 2