Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

Xamarin Forms - ReactiveUi ToDo List


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

Xamarin_Forms_ReactiveUi_ToDo_List

Table of Content

It is an advanced, Functional reactive MVVM and composable framework for all .Net frameworks.

ReactiveUi supports reactive programming to ease the implementation of the MVVM patterns in the application.

MVVM frame- Compared to other works, ReactiveUi is not very dictatorial.

Here, the Reactive Extensions (Rx) library is an appropriate use which, we declare callbacks and can manage asynchronous executions in the code and using the LinQ syntax, it does all these tasks.

It removes the unstructured & difficultly manageable code and makes it readable.

Generating ToDo List using ReactiveUi

For starting the project, we need to install 3 packages in the PCL project using NuGet package.

  1. ReactiveUi.XamForms package
  2. DynamicData package
  3. Sextant.XamForms package

And we’ll have to use the 8.0 or above version of C#.

Now, we have to create four folders as Managers, Models, ViewModels, and Views and add the appropriate file as mentioned below.

HomePage -> HomeViewModel handles the Todo List as it’s the home page.

ItemPage -> ItemVewModel adds and edits the single items.

The Item model represents the Todo item.

ItemManagers handles the collection of Todo.

Code for All added files:

IItemManager.cs

public class ItemManager : IItemManager
{
    public ItemManager()
    {
    	ItemChanges = _itemsCache.Connect().RefCount();
    }
    public Optional Get(string id) => _itemsCache.Lookup(id);
    public IObservable> ItemChanges { get; }
    public void AddOrUpdate(Item item) => _itemsCache.AddOrUpdate(item);
    public void Remove(Item item) => _itemsCache.Remove(item);
    private SourceCache _itemsCache = new SourceCache(item => item.Id);
}

 

Item.cs

public class Item : ReactiveObject
{
  public Item(string id, string title)
  {
     Id = id;
     Title = title;
  }
  public string Id { get; }
  public string Title { get; }
  public bool IsCompleted
  {
    get => _isCompleted;
    set => this.RaiseAndSetIfChanged(ref _isCompleted, value);
  }
  private bool _isCompleted;
}

 

HomeViewModel.cs

public class HomeViewModel : ViewModelBase
{
   public HomeViewModel(IParameterViewStackService navigationService, IItemManager 
    itemManager) : base(navigationService)
   {
     DeleteCommand = ReactiveCommand.Create(itemManager.Remove);
     itemManager
       .ItemChanges
       .Bind(out _items)
       .DisposeMany()
       .Subscribe()
       .DisposeWith(Subscriptions);            
    AddCommand = ReactiveCommand.CreateFromObservable(() => 
      NavigationService.PushModal());
    ViewCommand = ReactiveCommand.CreateFromObservable((item) =>
    {
      SelectedItem = null;
      return NavigationService.PushModal(new NavigationParameter()
      {
         { NavigationParameterConstants.ItemId , item.Id }
      });
    });
    this.WhenAnyValue(x => x.SelectedItem)
      .Where(x => x != null)
      .InvokeCommand(ViewCommand)
      .DisposeWith(Subscriptions);
  }
  public ReactiveCommand AddCommand { get; }
  public ReactiveCommand ViewCommand { get; }
  public ReactiveCommand DeleteCommand { get; }
  public Item SelectedItem
  {
     get => _selectedItem;
     set => this.RaiseAndSetIfChanged(ref _selectedItem, value);
  }
  public ReadOnlyObservableCollection Items => _items;
  public override string Id => "Reactive ToDo";
  private readonly ReadOnlyObservableCollection _items;
  private Item _selectedItem;
}

   

ItemViewModel.cs

public class ItemViewModel:ViewModelBase
{
  public ItemViewModel(IParameterViewStackService navigationService, IItemManager 
   itemManager) : base(navigationService)
  {
  	_itemManager = itemManager;
var canExecute = this.WhenAnyValue(x => x.Title, (title) => 
        !string.IsNullOrEmpty(title));
       SaveCommand = ReactiveCommand.Create(ExecuteSave, canExecute);
    
   CloseCommand = ReactiveCommand.CreateFromObservable(() =>     
     NavigationService.PopModal());
   SaveCommand
     .InvokeCommand(CloseCommand)
     .DisposeWith(Subscriptions);

   this.WhenAnyValue(x => x.ItemId)
      .Where(x => x != null)
      .Select(x => _itemManager.Get(x))
      .Where(x => x.HasValue)
      .Select(x => x.Value)
      .Subscribe(x =>
       {
           Title = x.Title;

       })
       .DisposeWith(Subscriptions);
  }
  public override IObservable WhenNavigatingTo(INavigationParameter parameter)
  {
     if (parameter.TryGetValue(NavigationParameterConstants.ItemId, out string itemId))
     {
     	ItemId = itemId;
     }
     return base.WhenNavigatedTo(parameter);
  }
  private void ExecuteSave() => _itemManager.AddOrUpdate(new Item(ItemId ??    
   Guid.NewGuid().ToString(), Title));
  public ReactiveCommand SaveCommand { get; }
  public ReactiveCommand CloseCommand { get; }
  public override string Id => string.Empty;
  public string Title
  {
     get => _title;
     set => this.RaiseAndSetIfChanged(ref _title, value);
  }
  private string ItemId
  {
  	get => _itemId;
       set => this.RaiseAndSetIfChanged(ref _itemId, value);
  }
  private string _title;
  private string _description;
  private readonly IItemManager _itemManager;
  private string _itemId;
}

 

ViewModelBase.cs

public abstract class ViewModelBase:ReactiveObject,IDisposable,INavigable
{
   protected ViewModelBase(IParameterViewStackService viewStackService) =>  
     NavigationService = viewStackService;
   public abstract string id { get; }
   public virtual IObservable WhenNavigatedFrom(INavigationParameter parameter) =>      
     Observable.Return(Unit.Default);
   public virtual IObservable WhenNavigatedTo(INavigationParameter parameter) =>  
     Observable.Return(Unit.Default);
   public virtual IObservable WhenNavigatingTo(INavigationParameter parameter) =>  
     Observable.Return(Unit.Default);
  protected IParameterViewStackService NavigationService { get; }
  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }
  protected virtual void Dispose(bool disposing)
  {
    if (disposing)
    {
      Subscriptions?.Dispose();
    }
  }
  protected readonly CompositeDisposable Subscription = new CompositeDisposable();
}

 

HomePage.xaml


<?xml encoding="utf-8" version="1.0">
<rxui:reactivecontentpage title="ToDo List" x:class="TodoList.Views.HomePage" x:name="homePage" x:typearguments="vm:HomeViewModel" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:rxui="clr-namespace:ReactiveUI.XamForms;assembly=ReactiveUI.XamForms" xmlns:vm="clr-namespace:TodoList.ViewModels" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <stacklayout padding="20">
        <collectionview itemssource="{Binding Items}" selecteditem="{Binding SelectedItem, Mode=TwoWay}" selectionmode="Single">
            <collectionview.itemslayout>
                <griditemslayout orientation="Vertical" verticalitemspacing="10" />
            </collectionview.itemslayout>
            <collectionview.itemtemplate>
                <datatemplate>
                    <frame style="{StaticResource CardFrameStyle}">
                        <frame.triggers>
                            <datatrigger binding="{Binding IsCompleted}" targettype="Frame" value="True">
                                <setter property="Opacity" value="0.2" />
                            </datatrigger>
                        </frame.triggers>
                        <stacklayout orientation="Horizontal">
                            <checkbox ischecked="{Binding IsCompleted}" />
                           

                            <label text="" verticaloptions="EndAndExpand">
                                <label.gesturerecognizers>
                                    <tapgesturerecognizer command="{Binding 
                                       Source={x:Reference homePage},               
                                       Path=BindingContext.DeleteCommand}" commandparameter="{Binding}" />
                                </label.gesturerecognizers>
                            </label>
                        </label></stacklayout><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
                    </label></frame><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
                </label></datatemplate><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
            </label></collectionview.itemtemplate><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
        </label></collectionview><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center"><button command="{Binding AddCommand}" style="{StaticResource CircularButtonStyle}" text="+"></button></label></stacklayout><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
</label></rxui:reactivecontentpage><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
</label></?xml>

ItemPage.xaml


Planning to Hire Xamarin App Development Company ? ?

Your Search ends here.


App.xaml:

newmobile2

Add Item

newmobile3

Items List

newmobile4

List after deleting item

Conclusion

Using ReactiveUi, we get the power to make reactive, testable, and composable Ui as we use the MVVM pattern. The Todo list is used to manage our day-to-day timetable to be followed. And using this, we can also make some applications that give responses quickly and in an understandable way.

Xamarin Forms - ReactiveUi ToDo List

Xamarin_Forms_ReactiveUi_ToDo_List

Table of Content

It is an advanced, Functional reactive MVVM and composable framework for all .Net frameworks.

ReactiveUi supports reactive programming to ease the implementation of the MVVM patterns in the application.

MVVM frame- Compared to other works, ReactiveUi is not very dictatorial.

Here, the Reactive Extensions (Rx) library is an appropriate use which, we declare callbacks and can manage asynchronous executions in the code and using the LinQ syntax, it does all these tasks.

It removes the unstructured & difficultly manageable code and makes it readable.

Generating ToDo List using ReactiveUi

For starting the project, we need to install 3 packages in the PCL project using NuGet package.

  1. ReactiveUi.XamForms package
  2. DynamicData package
  3. Sextant.XamForms package

And we’ll have to use the 8.0 or above version of C#.

Now, we have to create four folders as Managers, Models, ViewModels, and Views and add the appropriate file as mentioned below.

HomePage -> HomeViewModel handles the Todo List as it’s the home page.

ItemPage -> ItemVewModel adds and edits the single items.

The Item model represents the Todo item.

ItemManagers handles the collection of Todo.

Code for All added files:

IItemManager.cs

public class ItemManager : IItemManager
{
    public ItemManager()
    {
    	ItemChanges = _itemsCache.Connect().RefCount();
    }
    public Optional Get(string id) => _itemsCache.Lookup(id);
    public IObservable> ItemChanges { get; }
    public void AddOrUpdate(Item item) => _itemsCache.AddOrUpdate(item);
    public void Remove(Item item) => _itemsCache.Remove(item);
    private SourceCache _itemsCache = new SourceCache(item => item.Id);
}

 

Item.cs

public class Item : ReactiveObject
{
  public Item(string id, string title)
  {
     Id = id;
     Title = title;
  }
  public string Id { get; }
  public string Title { get; }
  public bool IsCompleted
  {
    get => _isCompleted;
    set => this.RaiseAndSetIfChanged(ref _isCompleted, value);
  }
  private bool _isCompleted;
}

 

HomeViewModel.cs

public class HomeViewModel : ViewModelBase
{
   public HomeViewModel(IParameterViewStackService navigationService, IItemManager 
    itemManager) : base(navigationService)
   {
     DeleteCommand = ReactiveCommand.Create(itemManager.Remove);
     itemManager
       .ItemChanges
       .Bind(out _items)
       .DisposeMany()
       .Subscribe()
       .DisposeWith(Subscriptions);            
    AddCommand = ReactiveCommand.CreateFromObservable(() => 
      NavigationService.PushModal());
    ViewCommand = ReactiveCommand.CreateFromObservable((item) =>
    {
      SelectedItem = null;
      return NavigationService.PushModal(new NavigationParameter()
      {
         { NavigationParameterConstants.ItemId , item.Id }
      });
    });
    this.WhenAnyValue(x => x.SelectedItem)
      .Where(x => x != null)
      .InvokeCommand(ViewCommand)
      .DisposeWith(Subscriptions);
  }
  public ReactiveCommand AddCommand { get; }
  public ReactiveCommand ViewCommand { get; }
  public ReactiveCommand DeleteCommand { get; }
  public Item SelectedItem
  {
     get => _selectedItem;
     set => this.RaiseAndSetIfChanged(ref _selectedItem, value);
  }
  public ReadOnlyObservableCollection Items => _items;
  public override string Id => "Reactive ToDo";
  private readonly ReadOnlyObservableCollection _items;
  private Item _selectedItem;
}

   

ItemViewModel.cs

public class ItemViewModel:ViewModelBase
{
  public ItemViewModel(IParameterViewStackService navigationService, IItemManager 
   itemManager) : base(navigationService)
  {
  	_itemManager = itemManager;
var canExecute = this.WhenAnyValue(x => x.Title, (title) => 
        !string.IsNullOrEmpty(title));
       SaveCommand = ReactiveCommand.Create(ExecuteSave, canExecute);
    
   CloseCommand = ReactiveCommand.CreateFromObservable(() =>     
     NavigationService.PopModal());
   SaveCommand
     .InvokeCommand(CloseCommand)
     .DisposeWith(Subscriptions);

   this.WhenAnyValue(x => x.ItemId)
      .Where(x => x != null)
      .Select(x => _itemManager.Get(x))
      .Where(x => x.HasValue)
      .Select(x => x.Value)
      .Subscribe(x =>
       {
           Title = x.Title;

       })
       .DisposeWith(Subscriptions);
  }
  public override IObservable WhenNavigatingTo(INavigationParameter parameter)
  {
     if (parameter.TryGetValue(NavigationParameterConstants.ItemId, out string itemId))
     {
     	ItemId = itemId;
     }
     return base.WhenNavigatedTo(parameter);
  }
  private void ExecuteSave() => _itemManager.AddOrUpdate(new Item(ItemId ??    
   Guid.NewGuid().ToString(), Title));
  public ReactiveCommand SaveCommand { get; }
  public ReactiveCommand CloseCommand { get; }
  public override string Id => string.Empty;
  public string Title
  {
     get => _title;
     set => this.RaiseAndSetIfChanged(ref _title, value);
  }
  private string ItemId
  {
  	get => _itemId;
       set => this.RaiseAndSetIfChanged(ref _itemId, value);
  }
  private string _title;
  private string _description;
  private readonly IItemManager _itemManager;
  private string _itemId;
}

 

ViewModelBase.cs

public abstract class ViewModelBase:ReactiveObject,IDisposable,INavigable
{
   protected ViewModelBase(IParameterViewStackService viewStackService) =>  
     NavigationService = viewStackService;
   public abstract string id { get; }
   public virtual IObservable WhenNavigatedFrom(INavigationParameter parameter) =>      
     Observable.Return(Unit.Default);
   public virtual IObservable WhenNavigatedTo(INavigationParameter parameter) =>  
     Observable.Return(Unit.Default);
   public virtual IObservable WhenNavigatingTo(INavigationParameter parameter) =>  
     Observable.Return(Unit.Default);
  protected IParameterViewStackService NavigationService { get; }
  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }
  protected virtual void Dispose(bool disposing)
  {
    if (disposing)
    {
      Subscriptions?.Dispose();
    }
  }
  protected readonly CompositeDisposable Subscription = new CompositeDisposable();
}

 

HomePage.xaml


<?xml encoding="utf-8" version="1.0">
<rxui:reactivecontentpage title="ToDo List" x:class="TodoList.Views.HomePage" x:name="homePage" x:typearguments="vm:HomeViewModel" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:rxui="clr-namespace:ReactiveUI.XamForms;assembly=ReactiveUI.XamForms" xmlns:vm="clr-namespace:TodoList.ViewModels" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <stacklayout padding="20">
        <collectionview itemssource="{Binding Items}" selecteditem="{Binding SelectedItem, Mode=TwoWay}" selectionmode="Single">
            <collectionview.itemslayout>
                <griditemslayout orientation="Vertical" verticalitemspacing="10" />
            </collectionview.itemslayout>
            <collectionview.itemtemplate>
                <datatemplate>
                    <frame style="{StaticResource CardFrameStyle}">
                        <frame.triggers>
                            <datatrigger binding="{Binding IsCompleted}" targettype="Frame" value="True">
                                <setter property="Opacity" value="0.2" />
                            </datatrigger>
                        </frame.triggers>
                        <stacklayout orientation="Horizontal">
                            <checkbox ischecked="{Binding IsCompleted}" />
                           

                            <label text="" verticaloptions="EndAndExpand">
                                <label.gesturerecognizers>
                                    <tapgesturerecognizer command="{Binding 
                                       Source={x:Reference homePage},               
                                       Path=BindingContext.DeleteCommand}" commandparameter="{Binding}" />
                                </label.gesturerecognizers>
                            </label>
                        </label></stacklayout><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
                    </label></frame><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
                </label></datatemplate><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
            </label></collectionview.itemtemplate><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
        </label></collectionview><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center"><button command="{Binding AddCommand}" style="{StaticResource CircularButtonStyle}" text="+"></button></label></stacklayout><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
</label></rxui:reactivecontentpage><label fontattributes="Bold" horizontaloptions="FillAndExpand" text="{Binding Title}" verticaloptions="Center">
</label></?xml>

ItemPage.xaml


Planning to Hire Xamarin App Development Company ? ?

Your Search ends here.


App.xaml:

newmobile2

Add Item

newmobile3

Items List

newmobile4

List after deleting item

Conclusion

Using ReactiveUi, we get the power to make reactive, testable, and composable Ui as we use the MVVM pattern. The Todo list is used to manage our day-to-day timetable to be followed. And using this, we can also make some applications that give responses quickly and in an understandable way.

Author Bio

Author

Author Name: Hemangi Tank

Hemangi Tank is an accomplished .NET professional specialized in the WPF platform. Taking a wide view of the process and development, she fabulously demonstrates concepts and shares impeccable insights on various platforms.