5

Using Dynamic Data in Xamarin Forms (Part 1)

 3 years ago
source link: https://www.xamboy.com/2021/01/20/using-dynamic-data-in-xamarin-forms-part-1/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

I have recently been exploring DynamicData and since I started using it, I can say that it has been a game changer in my applications. It is quite easy to use and provides a lot of flexibility when working with collections. So, I decided to write a series of articles about it:

  • Getting Started 
  • Filtering 
  • Grouping
  • Much More… 

Getting Started

What’s dynamic data?

Dynamic Data is a portable class library which brings the power of Reactive Extensions (Rx) to collections.”. With it, you will be able to perform complex operations such as a filter, grouping, add range, transform elements, etc in an effortless way.

How to use it?

For the following example, we are going to build a list of Restaurants. You can find the class used here.

1. Install the DynamicData Package in your Xamarin Forms project

2. Create an IObservable<ChangeSet>

There are two ways to create it:

  1. SourceCache<TObject, TKey> for items that have a unique key.
  2. SourceList<T> for items that don’t have a unique key.

In this specific case, I will use a SourceCache since each Restaurant has a unique id. t is also important to know that SourceCache performs much better than SourceList, so it is always wise to consider using it.

private SourceCache<Restaurant, string> _sourceCache = new SourceCache<Restaurant, string>(x => x.Id);

As you see when using the SourceCache I need to specify the type of my collection and its key.

3. Define the collection that you will use to display your items in the UI

public ReadOnlyObservableCollection<Restaurant> Restaurants => _restaurants; private readonly ReadOnlyObservableCollection<Restaurant> _restaurants;

4. Add items to the collection

In Dynamic Data to add items, you will add them to the SourceCache that we defined in step 2.

_sourceCache.AddOrUpdate(new List<Restaurant>() { new Restaurant("Yao","Casual","Asian Fusion","Dominican Republic"), new Restaurant("Chef Pepper","Casual","International","Dominican Republic"), new Restaurant("Bottega Fratelli","Formal","International","Dominican Republic"), new Restaurant("McDonalds","Fast Food","Burgers","United States"), new Restaurant("Burger King","Fast Food","Burgers","United States"), new Restaurant("Sushi Nation","Casual","Sushi","Venezuela"), new Restaurant("Pollo Victorina","Fast Food","Chicken","Dominican Republic"), new Restaurant("Pollo Rey","Fast Food","Chicken","Dominican Republic"), new Restaurant("Asadero Argetino","Formal","Meat","Dominican Republic"), new Restaurant("Hooters","Casual","Wings","United States"), new Restaurant("Andres Carne","Casual","Meat","Colombia"), new Restaurant("La Casita","Casual","Colombian Food","Colombia"), new Restaurant("Cielo","Formal","International","Colombia"), });

5. Connect the SourceCache and output the result to your collection by using Bind method.

_cleanUp = _sourceCache.Connect() .RefCount() .Bind(out _restaurants) .DisposeMany() .Subscribe();

_cleanUp is a variable to dispose the SourceCache

The full ViewModel code looks like this:

using System; using System.Collections.ObjectModel; using System.Reactive.Linq; using DynamicData; using System.Collections.Generic; using System.Threading.Tasks;

namespace DynamicDataGroupingSample { public class MainViewModel : IDisposable { public MainViewModel() { // Initial data _sourceCache.AddOrUpdate(new List<Restaurant>() { new Restaurant("Yao","Casual","Asian Fusion","Dominican Republic"), new Restaurant("Chef Pepper","Casual","International","Dominican Republic"), new Restaurant("Bottega Fratelli","Formal","International","Dominican Republic"), new Restaurant("McDonalds","Fast Food","Burgers","United States"), new Restaurant("Burger King","Fast Food","Burgers","United States"), new Restaurant("Sushi Nation","Casual","Sushi","Venezuela"), new Restaurant("Pollo Victorina","Fast Food","Chicken","Dominican Republic"), new Restaurant("Pollo Rey","Fast Food","Chicken","Dominican Republic"), new Restaurant("Asadero Argetino","Formal","Meat","Dominican Republic"), new Restaurant("Hooters","Casual","Wings","United States"), new Restaurant("Andres Carne","Casual","Meat","Colombia"), new Restaurant("La Casita","Casual","Colombian Food","Colombia"), new Restaurant("Cielo","Formal","International","Colombia"), });

_cleanUp = _sourceCache.Connect() .RefCount() .Bind(out _restaurants) .DisposeMany() .Subscribe(); }

public ReadOnlyObservableCollection<Restaurant> Restaurants => _restaurants; private SourceCache<Restaurant, string> _sourceCache = new SourceCache<Restaurant, string>(x => x.Id); private readonly ReadOnlyObservableCollection<Restaurant> _restaurants;

private readonly IDisposable _cleanUp; } }

6. Use the collection in your UI

<ListView ItemsSource="{Binding Restaurants}"> <ListView.ItemTemplate> <DataTemplate x:DataType="local:Restaurant"> <TextCell Text="{Binding Name}" Detail="{Binding Type}"/> </DataTemplate> </ListView.ItemTemplate> </ListView>

How to Add/Edit elements

The SourceCache provides a method to Update/Edit if the element exists it will update it, if not it will create a new one and add it to the list.

_sourceCache.Edit((update) => { update.AddOrUpdate(new Restaurant(name, "Casual", "Fast Food", "US")); });

NOTE: As you see you don’t need to re-assign it to the collection you are using in the UI, you just need to add it to the cache.

How to delete elements

_sourceCache.Edit((update) => { update.Remove(restaurant); });

Result

If you haven’t fallen in love with DynamicData yet, stay tuned for the next part of this series on Filtering, where you’ll see how easy it is to filter items.

Check the full source code here.

Happy Dynamic Data!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK