Krishna
Krishna

Reputation: 1985

Best place to load data from service in xamarin forms MVVM

What is the best place to call a service and load data in xamarin forms

  1. Till now I am calling the service in the view model constructor and loading data

  2. 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

Answers (2)

har07
har07

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

sriman reddy
sriman reddy

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

Related Questions