lundi 5 février 2018

Reactive UI with your UWP applications Example II (using your ViewModel) [XAML,C#,RxUI]

In the previous example we saw how to us Reactive UI on a auto complet, in this example we will see another example of how to Reactive UI on a ViewModel in your UWP application.

Here we will connect an property to a Service and a SelectedItem using ReactiveCommand.

First we will create a small class:

    public class MyItem
    {
        public int id { get; set; }
        public string name { get; set; }
    }


Next we will create a small service:

    
    public class MyItemService
    {
        public IObservable<IEnumerable<MyItem>> GetUpcomingItems(int index)
        {
            //get your items here
            //do your http call here
            return null;
        }
    }


Here is my ViewModel:


    public class MainViewModel : ViewModelBase
    {
        //My item loader
        public ReactiveCommand<int, IEnumerable<MyItem>> LoadMyItems
        {
            get;
        }

        //my selected item
        MyItem m_selectedItem;
        public MyItem MySelectedItem
        {
            get { return m_selectedItem; }
            set { RaisePropertyChanged("MySelectedItem"); }
        }

        //my service
        private MyItemService myItemService;

        public MainViewModel()
        {
            //init the serivce
            myItemService = new MyItemService();

            //getting items using the CreateFromObservable
            LoadMyItems = ReactiveCommand
                .CreateFromObservable((int index) =>
                    myItemService.GetUpcomingItems(index));

            //when the vm is activated bind the properties
            this.WhenActivated((CompositeDisposable disposables) =>
            {
                //init
                SelectedItem = null;

                //when SelectedItem has a value go to page
                this
                    .WhenAnyValue(x => x.SelectedItem)
                    .Where(x => x != null)
                    .Subscribe(x => LoadSelectedPage(x))
                    .DisposeWith(disposables);          
            });
        }


        public void LoadSelectedPage(MyItem item)
        {
            //load this page
        }
    }

The interesting part are the loading of the items using ReactiveCommand.CreateFromObservable this will start the loading once this property is binded to a ListView or GridView.

Next the SelectedItem and the this.WhenAnyValue(x => x.SelectedItem) will allow me to navigate or perform an action when this property has a value.

As you can see, Reactive UI  allows us to bind events in the ViewModel, of course you could have used ICommand or RelayCommand but I find Reactive UI to be a much more elegant solution!

Happy coding!