Reader small image

You're reading from  The MVVM Pattern in .NET MAUI

Product typeBook
Published inNov 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781805125006
Edition1st Edition
Languages
Right arrow
Author (1)
Pieter Nijs
Pieter Nijs
author image
Pieter Nijs

Pieter Nijs is a .NET consultant at Xebia in Belgium, with a keen interest in mobile and cloud development. He's been instrumental in diverse projects, from vast healthcare and telecom systems to compact LOB apps. Now, Pieter's exploring AI's potential to enhance customer projects innovatively. Passionate about technology, he actively experiments and shares knowledge as a conference speaker and trainer. Pieter has been awarded the Microsoft MVP Award since 2017, reflecting his unwavering passion and expertise in serving the community.
Read more about Pieter Nijs

Right arrow

Working with Remote Data

So far, we’ve dug deep into MVVM and .NET MAUI, covering everything from the basics of the MVVM design, from data binding and Dependency Injection to navigation and handling user input. But there’s one big piece of the puzzle we haven’t tackled yet: getting data from the internet.

It’s hard to imagine an app these days that doesn’t talk to an online service to grab fresh data. Adding backend communications also means we need to tackle some architectural challenges such as maintaining separation of concerns, building your app with maintainability in mind, and so on.

Here’s what we’ll dive into in this chapter:

  • Revisiting the model architecture
  • API communication with Refit
  • API communication from ViewModels

By the end of this chapter, our Recipes! app will be more than just a standalone thing. It’ll communicate with a backend service to fetch fresh data and push updates. We’...

Technical requirements

In this chapter, we update the general architecture of the Recipes! app to better facilitate communication with remote APIs. To ensure you’re on the same page, all resources and code snippets are available on GitHub: https://github.com/PacktPublishing/MVVM-pattern-.NET-MAUI/tree/main/Chapter10. If you wish to code along, start with the code in the Start folder, which has been refactored to serve as the foundation for this chapter. Upon completion, you can compare your work with the Finish folder to see the finalized version.

Revisiting the model architecture

In our journey so far, our model has been straightforward. We simply used services that read local JSON files and fed Data Transfer Objects (DTOs) directly to our ViewModels. But as we introduce remote data, this simplistic model won’t suffice.

A straightforward approach would be to make an API call directly within our service and pass the resulting DTOs to our ViewModels. However, leaning on the principle of SoC, I believe services shouldn’t be making API calls. Moreover, using API-specific DTOs directly within our ViewModels is a slippery slope. It tightly couples our application with the external API, which can lead to maintenance nightmares, especially if the API changes often or isn’t under our control.

Instead, I advocate for mapping these DTOs to Plain Old CLR Objects (POCOs), or entities or domain models – whatever you prefer to name them. The core idea? Work with types we own and control.

Tip

By keeping...

API communication with Refit

Up to this point, we’ve set up a neat architecture for our repositories, but they’re still missing the ability to talk to our API. To add this functionality, we could use HttpClient manually to make API calls and deserialize the response. While that’s entirely possible, it’s also cumbersome and prone to errors, not to mention it takes a lot of boilerplate code to get it right.

This is where Refit comes into the picture. Refit is a powerful library that simplifies API calls by providing a more declarative and less error-prone approach. Instead of writing tedious HTTP requests and responses, you just define a C# interface that maps to the API’s endpoints. Refit takes care of the underlying HttpClient calls, serialization, and deserialization for you, letting you focus on what matters – the logic of your application.

In this section, we’ll see how Refit can make our life easier by reducing code complexity...

API communication from ViewModels

When navigating to the RecipeDetailPage, you’ll see some data on the screen while the recipe is being loaded. The data being shown is the values defined as FallbackValue or TargetNullValue in the binding statements as a result of the data in RecipeDetailViewModel not being loaded yet. Although effective, I don’t think it looks pretty. Let’s see how we can improve this by showing a loading indicator while the data is being loaded.

Showing a loading indicator

One of the simplest yet effective ways to improve user experience is to provide visual feedback during API calls. Consider the following code snippet:

private bool _isLoading = true;
public bool IsLoading
{
    get => _isLoading;
    set => SetProperty(ref _isLoading, value);
}
private async Task LoadRecipe(string recipeId)
{
    IsLoading = true;
...
    await Task.WhenAll(loadRecipeTask...

Summary

We kicked off this chapter by revisiting the architecture of our Recipes! app to include repositories. This addition was aimed at adhering to the principle of SoC and minimizing our app’s dependency on the API itself. We also introduced the Result object, a transformative component in our error-handling strategy. This single object encapsulates both success and failure states, making our ViewModels more robust and intelligible. By using the Result object, we’ve made it easier to handle anticipated errors in a graceful manner, while still keeping exceptions reserved for critical failures.

After setting this architectural foundation, we moved on to explore the power and simplicity of Refit, a type-safe REST client. Refit has substantially streamlined the way we interact with APIs, making the code more readable and maintainable.

We also looked at how the Result object elegantly fits into our ViewModels, making it far easier to handle expected errors and providing...

Further reading

To learn more about the topics that were covered in this chapter, take a look at the following resources:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
The MVVM Pattern in .NET MAUI
Published in: Nov 2023Publisher: PacktISBN-13: 9781805125006
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Pieter Nijs

Pieter Nijs is a .NET consultant at Xebia in Belgium, with a keen interest in mobile and cloud development. He's been instrumental in diverse projects, from vast healthcare and telecom systems to compact LOB apps. Now, Pieter's exploring AI's potential to enhance customer projects innovatively. Passionate about technology, he actively experiments and shares knowledge as a conference speaker and trainer. Pieter has been awarded the Microsoft MVP Award since 2017, reflecting his unwavering passion and expertise in serving the community.
Read more about Pieter Nijs