Search

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday, September 26, 2019

Building a Cross Platform MVVM Pattern with ReactiveUI and Xamarin.Forms


As a Mobile Developer, when we start a new project, we always search and speak about application architecture. One of the most common choices in Xamarin.Forms is MVVM, this is due to the small amount of work to implement it, if we use ReactiveUI, we can additionally write applications in a reactive manner. It’s a time to check reactive UI how we can implement in Xamairn Forms project.
Reactive Extensions have been around for many years, and is available to most development environments. In this post, we are specifically going to look at Rx in terms of .NET development in Xamarin Forms. 
Rx is just a library for composing asynchronous, and event-based code with observables, and configuring it via LINQ. You can use LINQ to define criteria of when you want to perform an action, on the event. Rx can do more, but we will only look at the very basics in this post.
ReactiveUI allows you to combine the MVVM pattern with Reactive Programming using such features, as WhenAnyValue, ReactiveCommand, ObservableAsPropertyHelper, Binding and WhenActivated.
Create New Xamarin.Forms Application
In order to learn the ReactiveUI, let’s start creating a new Xamarin.Forms project using Visual Studio 2019 or VS for Mac. When using Visual Studio 2019 on a Windows machine, you will need to pair the mac machine for run and build the iOS platform.


Open Visual Studio 2019 >>Create a New Project or select "Open Recent Application" and the available templates will appear on a Windows like below. Select Xamarin.Form app and click on “Next”


ReactiveUI Nuget Package:
To implement ReactiveUI in our applications we will need to install the library. 
Step 1: Right click on Project and Click on Manage NuGet Packages for Solution option. 
Step 2: Search for “ReactiveUI.XamForms”.
Step 3: Install it for all of our projects with each platform. 


Create ViewModel :
ReactiveUI syntax for read-write properties is to notify Observers that a property has changed. Otherwise we would not be able to know when it was changed.
  • In cases when we don't need to provide for two-way binding between the View and the ViewModel, we can use one of many ReactiveUI Helpers, to notify Observers of a changing read-only value in the ViewModel.
  • RaiseAndSetIfChanged fully implements a Setter for a read-write property on a ReactiveObject, using CallerMemberName to raise the notification and the ref to the backing field to set the property.
  • ReactiveCommand is a Reactive Extensions and asynchronous aware implementation of the ICommand interface. ICommand is often used in the MVVM design pattern to allow the View to trigger business logic defined in the ViewModel
Let we create following property and command in the following ViewModel 
using System;
using System.Threading.Tasks;
using ReactiveUI;
using System.Reactive;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Reactive.Linq;

namespace ReactiveUIXamarin.ViewModel
{
    public class MainPageViewModel: ReactiveObject
    {
        private string _result;
        public string Result
        {
            get => _result;
            set => this.RaiseAndSetIfChanged(ref _result, value);
        }
        private string _username;
        public string UserName
        {
            get => _username;
            set => this.RaiseAndSetIfChanged(ref _username, value);
        }
        private string _password;
        public string Password
        {
            get => _password;
            set => this.RaiseAndSetIfChanged(ref _password, value);
        }
        private string _address;
        public string Address
        {
            get => _address;
            set => this.RaiseAndSetIfChanged(ref _address, value);
        }
        private string _phone;
        public string Phone
        {
            get => _phone;
            set => this.RaiseAndSetIfChanged(ref _phone, value);
        }
        public ReactiveCommand<Unit, Unit> RegisterCommand { get; }

        public MainPageViewModel()
        {
            RegisterCommand = ReactiveCommand
                .CreateFromObservable(ExecuteRegisterCommand);
        }

        private IObservable<Unit> ExecuteRegisterCommand()
        {
            Result = "Hello" + UserName + " Registration Success";
            return Observable.Return(Unit.Default);
        }
    }
  
}


Create UI View:
ReactiveUI allows you to create views using two different approaches. The recommended approach is using type-safe ReactiveUI bindings that can save you from memory leaks and runtime errors. The second approach is using XAML markup bindings.
The following sample UI created by recommended approach using type-safe ReactiveUI .
<rxui:ReactiveContentPage
  x:Class="ReactiveUIXamarin.MainPage"
  x:TypeArguments="vm:MainPageViewModel"          
  xmlns:vm="clr-namespace:ReactiveUIXamarin.ViewModel;assembly=ReactiveUIXamarin"
  xmlns:rxui="clr-namespace:ReactiveUI.XamForms;assembly=ReactiveUI.XamForms"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core" 
  xmlns="http://xamarin.com/schemas/2014/forms"
    ios:Page.UseSafeArea="true">
    <StackLayout>
        <Entry x:Name="Username" Placeholder="Username"/>
        <Entry x:Name="Password" Placeholder="Password"  />
        <Entry x:Name="Address" Placeholder="Address"  />
        <Entry x:Name="Phone" Placeholder="Phone Number" />
        <Button x:Name="Register" Text="Register" TextColor="White" BackgroundColor="Gray" />
        <Label x:Name="Result" />
    </StackLayout>
</rxui:ReactiveContentPage>


  • ContentPage should inherit from ReactiveContentPage<TViewModel> and we are going to use ReactiveUI Binding to bind our ViewModel to our View. 
  • Reactive binding is a cross platform way of consistently binding properties on your ViewModel to controls on your View. 
  • The ReactiveUI binding has a few advantages over the XAML based binding. The first advantage is that property name changes will generate a compile error rather than runtime errors.
  • One important think needs to follows while Binding, always dispose bindings via WhenActivated, or else the bindings leak memory.
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using ReactiveUIXamarin.ViewModel;
using ReactiveUI.XamForms;
using System.Reactive.Disposables;

namespace ReactiveUIXamarin
{

    public partial class MainPage : ReactiveContentPage<MainPageViewModel>
    {
        public MainPage()
        {
            InitializeComponent();
            ViewModel = new MainPageViewModel();

            // Setup the bindings.
            // Note: We have to use WhenActivated here, since we need to dispose the
            // bindings on XAML-based platforms, or else the bindings leak memory.
            this.WhenActivated(disposable =>
            {
                this.Bind(ViewModel, x => x.UserName, x => x.Username.Text)
                    .DisposeWith(disposable);
                this.Bind(ViewModel, x => x.Password, x => x.Password.Text)
                    .DisposeWith(disposable);
                this.Bind(ViewModel, x => x.Address, x => x.Address.Text)
                   .DisposeWith(disposable);
                this.Bind(ViewModel, x => x.Phone, x => x.Phone.Text)
                   .DisposeWith(disposable);
                this.BindCommand(ViewModel, x => x.RegisterCommand, x => x.Register)
                  
                    .DisposeWith(disposable);
                this.Bind(ViewModel, x => x.Result, x => x.Result.Text)
                   .DisposeWith(disposable);
            });
        }
    }
}


Output:
You can download the source code from github repository. When you run the application in an iPhone device, you will get the following output and click on Register, it will show the confirmation message like below screen.
Summary
This article has demonstrated and covers a little bit of what you can do when you combine the power of Reactiveui in Xamarin.Forms. I hope this article will help you to get started with awesome Framework.

27 comments:

  1. Replies
    1. Great Article Cloud Computing Projects

      Networking Projects

      Final Year Projects for CSE

      JavaScript Training in Chennai

      JavaScript Training in Chennai

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. Financial sector has undergone drastic technological shifts in a comparatively short span of time. The shifts have been incorporated because of Growing Technology, Customer Demands, etc. Take a glance over some of the legacy Cross-platform App Development Company. These are so dynamic and efficient that it will cost you less time, more functionality, good output returns.

    ReplyDelete
  3. Great blog, but developing an application in react native gives you fast and attractive app as compare to other frameworks, this makes react native best cross platform app development framework.

    ReplyDelete
  4. Woah!! Such a piece of the nice information you have shared here, I have read the entire post and I must say that the information is very helpful for me.
    Hire Xamarin Developer
    Xamarin Development Company

    ReplyDelete
  5. Change is the only constant. This applies in your professional life as well as personal life. Up-scaling yourself is a need nowadays, the reason is pretty simple, technology is evolving very quickly. I have listed top 10 trending technologies, which is expected to acquire a huge market in 2020.

    1. AI (Artificial Intelligence)
    2. Blockchain
    3. Augmented Reality and Virtual Reality
    4. Cognitive Cloud Computing
    5. Angular and React
    6. DevOps
    7. IoT (Internet of Things)
    8. Intelligent Apps (I – Apps)
    9. Big Data
    10. RPA (Robotic Process Automation)

    ReplyDelete
  6. Woah!! Such a piece of the nice information you have shared here, I have read the entire post and I must say that the information is very helpful for me.
    Hire Xamarin Developer
    Hire Xamarin Development Company
    Xamarin Development Company

    ReplyDelete
    Replies
    1. Maybe you should find some other way to advertise you company.

      Delete
  7. Thanks for this blog are more informative contents step by step. I here attached my site would you see this blog.

    7 tips to start a career in digital marketing

    “Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”.

    we have offered to the advanced syllabus course digital marketing for available join now.

    more details click the link now.

    https://www.webdschool.com/digital-marketing-course-in-chennai.html

    ReplyDelete
  8. Amazing article useful information.

    Web designing trends in 2020

    When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, WhatsApp, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

    we have offered to the advanced syllabus course web design and developing for available join now.

    https://www.webdschool.com/web-development-course-in-chennai.html

    ReplyDelete
  9. Xamarin app development is a cost effective solution to build fast and resoponsive web application go through Xamarin App Development Company

    ReplyDelete
    Replies
    1. Once again. How about finding some other way to advertise your company.

      Delete
  10. Nice and interesting post, I appreciate your hard work. keep it up…!!!

    Want to make custom website & application? Click here:
    Mobile Application Development
    Android Application Development
    iOS Application Development

    ReplyDelete
  11. Among many feature-packed mobile ap platforms, Xamarin development is a trending cross-platform framework. Xamarin facilitates Native like performance and makes it possible to access each and every native API.

    ReplyDelete
  12. Numerous organizations overall consider the alternative of a circulated committed group model in their business. This recruiting technique gives you an adaptable labor force that can be added or decreased, your group commitment in your venture, 24 hours workday, quicker issues goal, obligation, high mastery and sensible expenses. It is feasible to set aside to half of work exchange and an on location. All in all, it gives considerably more advantages to your business as opposed to on the off chance that you'd decide to employ specialists. Outstaffing is recruiting web engineers abroad from an nearshore and offshore development firm. Recruit offshore staff, and you can continue to work with similar group on additional undertakings. Building up a business dependent on reevaluating is definitely not a serious deal, it assists with setting aside cash and time and is not difficult to execute. Because of an assortment of offshore development models accessible, everybody can discover an alternative that fits him best. The offshore development model is ideal for organizations that know about the downsides of task the executives and programming development gives that may emerge during work. These organizations frequently focus on cost decrease keeping the nature of the item and are prepared to put resources into long haul business relations.

    ReplyDelete
  13. Businesses are now looking to develop their services with leading cross platform app development. This blog guides well on for to look into making the considerations for mobile app development with cross platform framework for app. We can get the solutions in Flutter app development, Android app development, iOS App Development

    ReplyDelete
  14. Apps have now taken over the conventional brick and mortar stores as the new millennials want to order everything online.
    On Demand App Development

    ReplyDelete
  15. Get the best of leading solutions in mobile app development blockchain app development and IoT Development that allows your business to scale up with leading technological advancements.

    ReplyDelete
  16. Hey! I agree with the commentators, a very useful article. In gratitude, I would like to advise you on one web page. It will be of interest to Java Script developers, because they have indicated the qualities and characteristics that they pay the most attention to when hiring, and a lot of other interesting information.

    ReplyDelete
  17. To get all your Product development requirements covered with the latest technological advancements such as IoT , Blockchain , Cloud Service , Mobile & Web development for your business. Hashstudioz Technologies brings you some of the leading solutions to Upgrade and Upscale your Business

    ReplyDelete
  18. Emblix Academy – Digital marketing institute in KPHB, we address all major and minor aspects required for any student’s advancement in digital marketing. Clutch USA named our Digital Marketing Institute the best SEO firm. for more info visit here :- https://emblixacademy.com/

    ReplyDelete
  19. It's actually an important blog entry. This blog momentarily clarifies about APP Development. This is one of the unmistakable programming dialects generally utilized. A debt of gratitude is in order for sharing this decent article. You can reffer more important things on this blog Mobile App Development Services

    ReplyDelete
  20. Thank you for sharing lot of information. Very informative post. Covered almost everything. Please Keep sharing such a useful content for us. please continue this work, also refer some informative blogs on Product Engineering Services for more contents about the product service based knowledge

    ReplyDelete
  21. Thank you so much for sharing. Keep updating your blog. It will very useful to the many users. But if you want to learn Current trends about Software Testing Services Visit this webpage I hope it would usefull for you.

    ReplyDelete